Majority Element

ID: 169; easy

Solution 1

func majorityElement(nums []int) int {
    m := make(map[int]int)
    for _,v := range nums {
        m[v]++
        if m[v] > len(nums)/2 {
            return v
        }
    }
    return -1
}

Solution 2

func majorityElement(nums []int) int {
    candidate, count := 0, 0
    for _,v := range nums {
        if count == 0 {
            candidate = v
        }
        if v == candidate {
            count++
        } else {
            count--
        }
    }
    return candidate
    
}

Boyer-Moore Voting Algorithm

Last updated