169. Majority Element

97 阅读1分钟

题目描述

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array.

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

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

解题思路1: map法

这个题目,我们最容易想到的就是使用一个hash, 存储元素和对应出现的次数, 然后我们在遍历hash, 拿到次数大于一半的元素值

示例代码1:

func majorityElement(_ nums: [Int]) -> Int {
    var hash: [Int: Int] = [:]
    var result = 0
    for i in nums {
        if let count = hash[i] {
            hash[i] = count + 1
        }else {
            hash[i] = 1
        }
    }

    hash.forEach { (key, value) in
        if value > nums.count / 2 {
            result = key
        }
    }
    return result
}

解题思路2: 摩尔投票法

对于这个hash方法的优化, 我们可以使用一个叫做 "摩尔投票"的方法来实现, 存储一个临时变量num, 以及计数的count, 然后我们遍历数组. 如果当前元素与num相等, 我们就把count++, 如果不相等,就把count--, 如果count等于0时, 我们就把num替换为当前元素, 直到最后我们就可以拿到num

示例代码2:

func majorityElement(_ nums: [Int]) -> Int {
    var num = nums[0]
    var count = 1

    for i in 1..<nums.count {
        let temp = nums[i]
        if temp == num {
            count += 1
        }else {
            count -= 1
        }

        if count == 0 {
            // 重置num 和 count
            num = nums[i]
            count = 1
        }
    }
    return num
}

解题思路3: 数学法

根据题意, 我们可以知道肯定有一个元素的个数大于1/2, 我们可以另辟蹊径, 直接给数组排序, 因为有1/2 都是这个元素, 所以: 这个元素肯定在 数组的1/2处

示例代码3:

func majorityElement(_ nums: [Int]) -> Int {
    let temp = nums.sorted { (a, b) -> Bool in
        return a < b
    }
    return temp[temp.count/2]
}