[LeetCode] 137. Single Number II 单独数 II

Posted 轻风舞动

tags:

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

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

 解法:参考

Java:

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

Python:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        x1, x2, mask = 0, 0, 0
        for i in nums:
            x2 ^= x1 & i;
            x1 ^= i;
            mask = ~(x1 & x2);
            x2 &= mask;
            x1 &= mask;
        return x1  

C++:

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

C++:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int a = 0, b = 0;
        for (int i = 0; i < nums.size(); ++i) {
            b = (b ^ nums[i]) & ~a;
            a = (a ^ nums[i]) & ~b;
        }
        return b;
    }
};

  

  

 

 

类似题目:

[LeetCode] 136. Single Number 单独数

[LeetCode] 260. Single Number III 单独数 III

 

All LeetCode Questions List 题目汇总

以上是关于[LeetCode] 137. Single Number II 单独数 II的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-137-Single Number II]

leetcode-137-Single Number II

Leetcode137. Single Number II

LeetCode-137-Single Number II

[LeetCode] 137. Single Number II (位运算)

[LeetCode] 137. Single Number II 单独数 II