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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-single-number-ii/
