【LeetCode】Single Number

 这道题面试的时候被考到了,可惜当时被考到的时候还没做过这道,面试官提示了我要用异或,我想了老半天才想出来。。。有三种解法,

1、计数排序 + 一次遍历:  time-complexity: O(n), space-complexity: O(max_int);

2、哈希表: time-complexity: O(n), space-complexity: O(max_int);

3、异或:time-complexity: O(n), space-complexity: O(n);

class Solution {
public:
    int singleNumber(int A[], int n) {
        int result = 0x00000000;
        
        while (n != 0) result = result ^ A[--n];
        
        return result;
    }
};



你可能感兴趣的:(【LeetCode】Single Number)