您的位置:首页 > 职场人生

面试题:找出数组中只出现一次的数字(二)

2015-08-27 22:36 417 查看
难度:中等

一个整数数组,除了一个数之外所有数字都出现了3次,找出这个数字来。

注意: 你的算法应该是线性运行复杂度,且不能使用额外内存空间。

答案:

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

for (int i = 0; i < nums.length; i++) {
// twos holds the num that appears twice
twos |= ones & nums[i];

// ones holds the num that appears once
ones ^= nums[i];

// threes holds the num that appears three times
threes = ones & twos;

// if num[i] appears three times
// doing this will clear ones and twos
ones &= ~threes;
twos &= ~threes;
}

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