1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @Title: 数组中出现次数超过一半的数字 (数组中出现次数超过一半的数字  LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-02-22 10:56:42
// @Runtime: 12 ms
// @Memory: 5.9 MB
func majorityElement(nums []int) int {
    ans, votes :=nums[0], 1
    for i:=1;i<len(nums);i++ {
        // fmt.Println(nums[i], votes)
        if nums[i] == ans {
            votes++
        } else { // first case
            votes--
        }
        
        if votes == 0  {
            ans = nums[i]
            votes = 1
        }
    }

    return ans
}