Leetcode 136. Single Number

Leetcode 136. Single Number_第1张图片
方法1: bit manipulation。利用xor。xor是相同0,不同为1。所以5 xor 5 = 0,但是any 不为0的number xor 0都是该number本身。因此我们只要简单的把所有的数字xor起来就可以得到那个appear once的数字。时间复杂n,空间复杂1.

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

总结:

你可能感兴趣的:(Leetcode,math,bitmap)