137. 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?
数组仅有一个数出现一次,其他的出现3次。找出那个出现一次的数。依然使用位运算来求解。
统计每一位上1出现的次数,1出现次数不为3的倍数的位所组成的数即为要找的数。
代码实现:
1 class Solution { 2 public: 3 int singleNumber(vector<int>& nums) { 4 int n = nums.size(); 5 int ones = 0; 6 int twos = 0; 7 int xthrees = 0; 8 for(int i = 0; i < n; ++i) 9 { 10 twos |= (ones & nums[i]); 11 ones ^= nums[i]; 12 xthrees = ~(ones & twos); 13 ones &= xthrees; 14 twos &= xthrees; 15 } 16 return ones; 17 } 18 };