Single Number II
题目要求:
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
明确一下要求:
1. 线性时间复杂度 O(n)
2. 常量的空间复杂度O(1)
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 };