LeetCode Problem 136:Single Number

描述: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? app

題目要求O(n)時間複雜度,O(1)空間複雜度。spa

思路1:初步使用暴力搜索,遍歷數組,發現兩個元素相等,則將這兩個元素的標誌位置爲1,最後返回標誌位爲0的元素便可。時間複雜度O(n^2)沒有AC,Status:Time Limit Exceedcode

 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)blog

 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 };
相關文章
相關標籤/搜索