您的位置:首页 > 其它

[LeetCode] - Single Number II

2014-01-14 12:28 429 查看
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的情况也可以推广到n,这样的话就需要n个变量用来存储状态了。还有值得注意的是,twos,ones,threes这个顺序一定不能搞乱,先更新twos,再更新ones,要么twos就一直是0了。

public class Solution {
public int singleNumber(int[] A) {
int ones=0, twos=0, threes=0;

for(int i=0; i<=A.length-1; i++) {
twos |= ones & A[i];        // get 1s that have appeared two times
ones ^= A[i];               // get 1s that have appeared one time
threes = ~(twos & ones);    // get 1s that have appeared three times
ones &= threes;             // mod 3
twos &= threes;             // mod 3
}

return ones;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: