求数组中仅出现一次的数字

大神解法:

位运算:

一个数和 0 做 XOR 运算等于本身:a⊕0 = a
一个数和其本身做 XOR 运算等于 0:a⊕a = 0
XOR 运算满足交换律和结合律:a⊕b⊕a = (a⊕a)⊕b = 0⊕b = b
将所有数字按照顺序做异或运算,最后剩下的结果即为唯一的数字

class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for(int num: nums) {
            ans ^= num;
        }
        return ans;
    }
}

作者:guanpengchn
链接:https://leetcode-cn.com/problems/single-number/solution/hua-jie-suan-fa-136-zhi-chu-xian-yi-ci-de-shu-zi-b/

小白解法:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for i in nums:
            if nums.count(i)==1:
                return i

 

posted @ 2020-09-15 17:41  lagjaflgjfl  阅读(63)  评论(0)    收藏  举报