Single Number II

題目要求:app

Given an array of integers, every element appears three times except for one. Find that single one.spa

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?code

 

明確一下要求:blog

1.  線性時間複雜度 O(n)three

2.  常量的空間複雜度O(1)element

 

 1 class Solution {
 2 public:
 3     int singleNumber(int A[], int n) {
 4         // Note: The Solution object is instantiated only once and is reused by each test case.
 5         int ones = 0, twos = 0;
 6         int commonBitMask = 0;
 7         for (int i = 0; i < n; ++i) {
 8             twos |= (ones & A[i]); //  此時twos中包含二次和三次的位
 9             ones ^= A[i]; //此時ones中包含一次和三次的位
10             commonBitMask = ~(twos & ones); // 過濾掉三次的位
11             ones &= commonBitMask;
12             twos &= commonBitMask;
13         }
14         return ones;
15     }
16 };
相關文章
相關標籤/搜索