# 剑指 Offer 39. 数组中出现次数超过一半的数字 --- ```javascript= 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例 1: 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2 ``` :::success ```go= // 因为重复值超过了一半 肯定中间值也是 /* [1, 2, 2, 2, 2, 2, 3, 4, 5] num1[9/2]=num1[4]=2 [1, 2, 2, 2, 2, 2, 3, 4,5,6] num1[10/2]=num1[5]=2 [1, 2, 2, 2, 2, 2, 2, 4,5,6] num1[10/2]=num1[5]=2 */ func majorityElement(nums []int) int { sort.Ints(nums) return nums[len(nums)/2] } // 不断的比较出现次数最多的数字 func majorityElement(nums []int) int { cmp := nums[0] votes := 1 for i := 1; i < len(nums); i++ { if votes == 0 { cmp = nums[i] } if nums[i] == cmp { votes++ } else { votes-- } } return cmp } ``` ::: ###### tags: `LeeCode`