Leetcode Single Number II

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?


解题思路:

参考答案的,想不出来。

  1. ones   代表第ith 位只出现一次的掩码变量
  2. twos  代表第ith 位只出现两次次的掩码变量
  3. threes  代表第ith 位只出现三次的掩码变量

Java code :

public int singleNumber(int[] nums) {
        int ones = 0, twos = 0, threes = 0;
        for (int i = 0; i < nums.length; i++) {
            twos |= ones & nums[i];
            ones ^= nums[i];
            threes = ones & twos;
            ones &= ~threes;
            twos &= ~threes;
        }
        return ones;
    }

Reference:

1. http://www.cnblogs.com/springfor/p/3870863.html

2. http://www.programcreek.com/2014/03/leetcode-single-number-ii-java/

3. http://www.acmerblog.com/leetcode-single-number-ii-5394.html

 

posted @ 2015-10-10 13:03  茜茜的技术空间  阅读(111)  评论(0编辑  收藏  举报