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 };
相关文章
相关标签/搜索