前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q169 Majority Element

Q169 Majority Element

作者头像
echobingo
发布2018-04-25 16:58:30
8560
发布2018-04-25 16:58:30
举报

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实现:
代码语言:javascript
复制
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代码实现,不过时间复杂度比较高:
代码语言:javascript
复制
return sorted(nums)[len(nums)/2]
  1. 空间复杂度为 O(1) 的完美算法(火拼算法,势力相等则抵消):
代码语言:javascript
复制
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 次的条件,只不过我想不到。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • Python实现:
  • 补充:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档