[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

解法一

思路

看到这个题,直接想到用hashmap来存<数字,出现次数>这样的键值对,遍历一遍数组,当存完后,遍历一遍hashmap,找出value>n/2对应的key即可。

代码

class Solution {
    public int majorityElement(int[] nums) {
        int res = -1;
        Map<Integer,Integer> count = new HashMap<>();
        for(int i = 0; i < nums.length; i++) {
            count.put(nums[i], count.getOrDefault(nums[i],0)+1);
        }
        for(int num : nums){
            if(count.get(num)>nums.length/2){
                res = num;
                break;
            }
        }
        return res;
    }
}

解法二

思路

直接对数组进行排序,然后直接返回第n/2个元素即可(因为这个题的案例是保证存在的,所以这样绝对可以找到)

代码

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return (nums[nums.length/2]);
    }
}

解法三

思路

直接对数组的每个元素的每一位进行遍历(用两个for循环),因为我们要找数组中出现频次大于n/2的数字,所以对于32中的任何一位,总会有0或1超过一半的情形,所以我们统计每一位上0或1的频次,频次较高的就是res这一位上的数组。很巧妙~~

代码

class Solution {
    public int majorityElement(int[] nums) {
        int res = 0;
        int n = nums.length;
        for(int i = 0; i < 32; i++) {
            int ones = 0, zeroes = 0;
            for(int num : nums) {
                if(ones > n/2 || zeroes > n/2) break;
                if((num & (1 << i)) != 0) ones++;
                else zeroes++;
            }
            if(ones > zeroes) res |= (1 << i);
        }
        return res;
    }
}

解法四

思路

求一个频次超过n/2的数,我们可以设置一个计数器,指向第一个数字,将第一个数字设为res,并将计数器初始为1,如果下一个数字与该数字相同,则加1,不同则减1;如果到某个数字,计数器为0,则将该数字设为res。原理:如果到某个数字计数器为0,则相当于在整个数组中删去了相同数量的众数与非众数,那么数组中剩下的数字中众数仍然过半,仍能找到它。

代码

class Solution {
    public int majorityElement(int[] nums) {
        int res = 0;
        int cnt = 0;
        for(int num:nums) {
            if(cnt == 0) {res = num; cnt++;}
            else if(num == res) cnt++;
            else cnt--;
        }
        return res;
    }
}

转载于:https://www.cnblogs.com/shinjia/p/9759930.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值