Contents

137. Single Number II

Problem

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

Input: [2,2,3,2]
Output: 3
Input: [0,1,0,1,0,1,99]
Output: 99

Solution

Sort array and walk

func singleNumber(nums []int) int {
    sort.Ints(nums)
    
    for idx:=0; idx<len(nums); idx+=3 {
        if idx<len(nums)-3 && nums[idx]!=nums[idx+2] {
            return nums[idx]
        }
    }
    
    return nums[len(nums)-1]
}