[leetcode]169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appearsmore than [ n/2 ] times.

You may assume that the array is non-empty and the majority element always exist in the array.

题意:给定一个大小为n的数组,查找多数元素。大多数元素是出现频率超过[N / 2]次的元素。假设数组是非空的,并且多数元素总是存在于数组中。

看见题目直接暴力解决,将数组的字面值作为map的key,出现次数作为value全部统计一次,出现次数一旦大于n/2就返回这个key。

    public int majorityElement(int[] nums) {
	Arrays.sort(nums);
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        map.put(nums[0], 1);
        int count = 0;
        for (int i = 1; i < nums.length; i++) {
	    if(nums[i]==nums[i-1]){
	        count = map.get(nums[i-1])+1;
	        if(count>nums.length/2){return nums[i];}
		map.remove(nums[i-1]);
		map.put(nums[i], count);
	    }else{
	        map.put(nums[i], 1);
	    }
	}
        return -1;
    }

然后再回头看看题目,这个元素一定存在,而且数组不为空,也就是说当数组长度为偶数时不可能出现类似[1,1,2,2]的数组,而且这个元素的出现的次数是大于n/2次的。于是经过排序后就会出现一个神奇的事情,下标为n/2的那个元素就是那个出现次数最多的那个元素。

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

也许你会出现这样的疑问当n=3时,nums[1.5]会出现什么情况,别担心他会给你返回nums[(int)1.5]=nums[1]的值正好是那个中间值。问题得到高效简洁的解决。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值