描述: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?
題目要求O(n)時間復雜度,O(1)空間復雜度。
思路1:初步使用暴力搜索,遍歷數組,發現兩個元素相等,則將這兩個元素的標志位置為1,最后返回標志位為0的元素即可。時間復雜度O(n^2)沒有AC,Status:Time Limit Exceed
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 5 vector <int> flag(n,0); 6 7 for(int i = 0; i < n; i++) { 8 if(flag[i] == 1) 9 continue; 10 else { 11 for(int j = i + 1; j < n; j++) { 12 if(A[i] == A[j]) { 13 flag[i] = 1; 14 flag[j] = 1; 15 } 16 } 17 } 18 } 19 20 for(int i = 0; i < n; i++) { 21 if(flag[i] == 0) 22 return A[i]; 23 } 24 } 25 };
思路2:利用異或操作。異或的性質1:交換律a ^ b = b ^ a,性質2:0 ^ a = a。於是利用交換律可以將數組假想成相同元素全部相鄰,於是將所有元素依次做異或操作,相同元素異或為0,最終剩下的元素就為Single Number。時間復雜度O(n),空間復雜度O(1)
1 class Solution { 2 public: 3 int singleNumber(int A[], int n) { 4 5 //異或 6 int elem = 0; 7 for(int i = 0; i < n ; i++) { 8 elem = elem ^ A[i]; 9 } 10 11 return elem; 12 } 13 };
