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

难度:中等

一个整数数组,除了一个数之外所有数字都出现了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;
    }
}

 

posted @ 2015-08-27 22:36  -小城-  阅读(183)  评论(0编辑  收藏  举报