首页 > 编程语言 > 详细

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

时间:2015-08-28 00:23:04      阅读:272      评论:0      收藏:0      [点我收藏+]

难度:中等

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

 

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

原文:http://www.cnblogs.com/wan1976/p/4764850.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!