137. Single Number II - Medium

Posted fatttcat

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了137. Single Number II - Medium相关的知识,希望对你有一定的参考价值。

Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

 

reference: https://leetcode.com/problems/single-number-ii/discuss/43302/Accepted-code-with-proper-Explaination.-Does-anyone-have-a-better-idea

对于每一个元素,统计其出现次数,若出现次数达到3,则置为0,最后所有元素的次数都为0,除了只出现一次的元素是1

即0->1->2->0,如果用二进制表示:00->01->10->00。换一种方便的表示方法:00->10->01->00,这样可以用两个参数ones twos来表示,最后返回ones就是只出现一次的数字

ones和twos的变化过程:

  0     0   (初始)

0->1  0->0

1->0  0->1

0->0  1->0

遍历整个数组,对每一个元素,先存入ones,再清空ones存入twos,再清空twos

time: O(n), space: O(1)

class Solution {
    public int singleNumber(int[] nums) {
        int ones = 0, twos = 0;
        for(int k : nums) {
            ones = (ones ^ k) & ~twos;
            twos = (twos ^ k) & ~ones;
        }
        return ones; 
    }
}

 

另一种理解方法:模拟三进制

class Solution {
    public int singleNumber(int[] nums) {
        int one = 0, two = 0, three = 0;
        for(int i = 0; i < nums.length; i++) {
            two |= one & nums[i];
            one ^= nums[i];
            three = one & two;
            one &= ~three;
            two &= ~three;
        }
        return one;
    }
}

 

以上是关于137. Single Number II - Medium的主要内容,如果未能解决你的问题,请参考以下文章

137. Single Number II

137. Single Number II(js)

137. Single Number II

137.Single Number II

LeetCode136 Single Number, LeetCode137 Single Number II, LeetCode260 Single Number III

[leetcode-137-Single Number II]