简繁EN

LeetCodeNo. 129

[LeetCode with Python] 137. Single Number II

Contents

Problem

Problem page: https://leetcode.com/problems/single-number-ii/
Topics: Bit Manipulation
Difficulty: Medium
Similar problems: (M) Single Number, (M) Single Number III

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?


Analysis

In Single Number, each element appears twice except for one. In this problem, each element appears three times except for one.
An int has 32 bits, so I can use 32 variables to count how many of the N elements have a 1 at each bit position. Then I take each count mod 3. If the result is 1, that bit is 1 in the binary representation of the element I'm looking for. But this probably isn't the best approach. There should be a better algorithm. I'm still thinking about it.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
len_A = len(A)
counts = [0] * 32
res = 0
for i in range(0, 32):
for num in A:
#num = long(num) # it will make time limit exceeded
counts[i] += (num>>i) & 1
res |= ((counts[i] % 3) << i)
if 0 != counts[31] % 3:
res -= pow(2, 32) ######
return res

Article link: https://xnerv.wang/en/leetcode-single-number-ii/