【LeetCode】Single Number

 這道題面試的時候被考到了,惋惜當時被考到的時候還沒作過這道,面試官提示了我要用異或,我想了老半天才想出來。。。有三種解法,面試

一、計數排序 + 一次遍歷:  time-complexity: O(n), space-complexity: O(max_int);spa

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

三、異或: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;
    }
};
相關文章
相關標籤/搜索