美文网首页LeetCode By Go
[LeetCode By Go 16]136. Single N

[LeetCode By Go 16]136. Single N

作者: miltonsun | 来源:发表于2017-08-17 10:08 被阅读28次

    题目

    Given an array of integers, every element appears twice except for one. Find that single one.

    Note:
    Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

    中文大意

    给定一个整数数组,里面只有一个数只出现一次,其余的数都出现两次,找出只出现一次的数。

    解题思路

    采用异或运算^
    a ^ a = 0
    a ^ 0 = a
    a ^ b ^ c = a ^ (b ^ c)
    因此所有数进行异或,最终得到的就是只出现一次的数

    代码

    func singleNumber(nums []int) int {
        var ret int
        ret = 0
        for _,v := range nums {
            ret = ret ^ v
        }
        return ret
    }
    

    相关文章

      网友评论

        本文标题:[LeetCode By Go 16]136. Single N

        本文链接:https://www.haomeiwen.com/subject/lpjgrxtx.html