目录
数组中出现次数超过一半的数字
访问量:916

一、简介

给一个长度为 n 的数组,数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

二、实现

思路:使用消除法,如果两个数不相等,就消去这两个数,最后剩下的数字为需求找的数字

/**
 * 
 * @param numbers int整型一维数组 
 * @return int整型
*/
func MoreThanHalfNum_Solution( numbers []int ) int {
    // write code here
    curNum := numbers[0]
    curTimes := 1
    
    for i:=1; i< len(numbers); i++ {
        if curTimes == 0 {
            curNum= numbers[i]
            curTimes = 1
        } else if numbers[i] == curNum {
            curTimes ++
        } else {
            curTimes --
        }
    }
    
    return curNum
}