Post

Leetcode - 137. Single Number II

Leetcode - 137. Single Number II

Hits

  • Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

    You must implement a solution with a linear runtime complexity and use only constant extra space.

Solution

1
2
3
4
5
6
7
8
9
10
func singleNumber(nums []int) int {
    ones, twos := 0, 0

    for _, num := range nums {
        ones = (ones ^ num) &^ twos
        twos = (twos ^ num) &^ ones
    }

    return ones
}
This post is licensed under CC BY 4.0 by the author.