Loading

[LeetCode] 169. Majority Element(主元素)

Description

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

给一个长度为 n 的数组,找到该数组的主元素。主元素是在数组中出现的次数大于 ⌊ n/2 ⌋ 的元素。

You may assume that the array is non-empty and the majority element always exist in the array.

你可以假设数组非空,且主元素一定存在。

Examples

Example 1

Input: [3,2,3]
Output: 3

Example 2

Input: [2,2,1,1,1,2,2]
Output: 2

Solution

这题有个显而易见的做法就是统计每个数字出现的频率,然后找出频率最大的。这需要额外的空间记录这些频率信息。之前有看过另外一种只需要常数额外空间的解法,大致思路如下:

  1. 准备两个变量,一个记录结果,一个记录该结果对应的频率,初始时,设定第一个元素为结果,频率为 1。(题目假定数组非空,所以可以这么做)

  2. 遍历之后的元素,元素与结果相同,频率 +1,否则频率 -1。如果频率扣减至 0,则设置当前元素为结果并重置频率。

  3. 数组遍历完成后,最后的结果即为所求。

代码如下:

class Solution {
    fun majorityElement(nums: IntArray): Int {
        var result = nums[0]
        var count = 1

        for (i in 1..nums.lastIndex) {
            if (nums[i] == result) {
                count++
            } else {
                count--
            }
            if (count == 0) {
                result = nums[i]
                count = 1
            }
        }
        return result
    }
}
posted @ 2020-10-10 10:10  Zhongju.copy()  阅读(84)  评论(0编辑  收藏  举报