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?
思路:
Step1:从Single Number我们知道,通过易或操作可以用一个int存储出现过单数次的
Step2:我们可以通过与单数出现的做与,来获得出现过双数次的数
Step3:想办法把Step1 int中出现三次的去掉。
class Solution { public: int singleNumber(int A[], int n) { int once = 0; int twice = 0; for (int i = 0; i < n; i++) { twice |= once & A[i]; //the num appeared 2 times once ^= A[i]; //the num appeared 1 times int not_three = ~(once & twice); //the num not appeared 3 times once = not_three & once; //remove num appeared 3 times from once twice = not_three & twice; //remove num appeared 3 times from twice } return once; } };
时间: 2024-11-05 02:36:14