LeetCode刷题169. 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.

Example 1:

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

Example 2:

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

解题思路:找到数组中出现次数大于⌊ n/2 ⌋的元素,也就是说要统计一下数组中各元素出现的次数。我最先想到的方法就是利用一个HashMap<K,V>来计数,Key为数组中的元素,Value为出现次数,完成以后对HashMap遍历一次就可以轻松得到答案。
代码如下:

class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else{
                map.put(nums[i],1);
            }
        }
        for(Integer key : map.keySet()){
            if(map.get(key) > nums.length/2){
                return (int)key;
            }
        }
        return 0;
    }
}

分析:这个解法的时间复杂度O(n),空间复杂度O(n)。看了下讨论中各位大佬的方法,其中支持最高的方法在空间复杂度上提高到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;
    }
}

其实这个算法是经典的摩尔投票算法。原理也比较简单,每找出两个不同的num,就成对删除即count–,最终剩下的一定那个元素的个数绝对超过了⌊ n/2 ⌋,即为所求。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

James Shangguan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值