NOTE

Single Number

Find the element that appears only once using counting or XOR.

Data Structures & AlgorithmsCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Problem Description

Given a non-empty integer array, every element appears twice except for one. Find the element that appears only once.

2. Approach

  1. Approach 1
    • Use a map to count each element
  2. Approach 2
    • XOR all elements in the array. Since equal elements XOR to 0, and 0 XOR any number is still that number, the final result must be the number that appears only once

3. Implementation

3.1. Brute Force

func singleNumber(nums []int) int {
    count := make(map[int]int, 0)
    for _, num := range nums {
        count[num]++
    }

    for _, num := range nums {
        if count[num] == 1 {
            return num
        }
    }
    return 0
}

3.2. XOR

func singleNumber(nums []int) int {
    res := 0

    for _, num := range nums {
        res ^= num
    }

    return res
    
}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub