标签:leetcode
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?
用 ones, twos, threes 分别记录数字在二进制表示中对应位置 1 出现的次数。变量更新如下:首先更新 twos, 对应位置出现两次的为上一次对应位置出现两次的加上一次出现一次的和新的数的与,ones 为对应位置出现一次的为上一次出现一次的异或上新的数,threes 为对应位置出现了一次的再与上出现了两次的位置。
然后再把 ones 和 twos 中 含有 threes 中 1 的位置的那些去掉。
这道题的位运算很微妙,值得好好体会。你可以想想 ones、twos 和 threes 是怎么来的?计算的先后顺序能不能变化?threes 为什么可以用 ones 和 twos 的值来算?
C++:
class Solution { public: int singleNumber(int A[], int n) { int ones = 0, twos = 0, threes = 0; for(int i = 0;i < n;++i) { twos = twos | ones & A[i]; ones = ones ^ A[i]; threes = ones & twos; ones = ones & ~threes; twos = twos & ~threes; } return ones; } };
Python:
class Solution: # @param A, a list of integer # @return an integer def singleNumber(self, A): ones = 0 twos = 0 thress = 0 for i in range(0,len(A)): twos = twos | ones & A[i] ones = ones ^ A[i] threes = ones & twos ones = ones & ~threes twos = twos & ~threes return ones
标签:leetcode
原文地址:http://blog.csdn.net/jcjc918/article/details/43915525