Q169 Majority Element

时间:2022-05-11
本文章向大家介绍Q169 Majority Element,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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.

解题思路:

将每个元素出现的次数用 Map 保存起来,返回出现次数最多的元素。

时间复杂度:O(n);空间复杂度:O(n)

Python实现:
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = {}
        maxE = maxV = 0
        for val in nums:  # 统计每个元素的个数
            if count.get(val):
                count[val] += 1
            else:
                count[val] = 1
        for key, val in count.items():
            if val > maxV:
                maxE, maxV = key, val
        return maxE

a = [3,2,3,3]
b = Solution()
print(b.majorityElement(a)) # 3
补充:
  1. 一行Python代码实现,不过时间复杂度比较高:
return sorted(nums)[len(nums)/2]
  1. 空间复杂度为 O(1) 的完美算法(火拼算法,势力相等则抵消):
public class Solution {
    public int majorityElement(int[] num) {
        int major=num[0], count = 1;
        for(int i=1; i<num.length;i++){
            if(count==0){
                count++;
                major=num[i];
            }else if(major==num[i]){
                count++;
            }else count--;            
        }
        return major;
    }
}

方法2完美地抓住了列表中元素超过 n/2 次的条件,只不过我想不到。