169.求众数

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在众数。

示例 1:

输入: [3,2,3]
输出: 3

示例 2:

输入: [2,2,1,1,1,2,2]
输出: 2

方法1

分析:通过众数的性质可知,如果一个数是众数,通过排序之后那么该众数必然等于=nums[(int)Math.floor(nums.length/2)]。时间复杂度O(n)

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
		int floor=(int)Math.floor(nums.length/2);
		int count=0;
		for(int i=0;i<nums.length;i++) {
			if(nums[i]==nums[floor])
				count++;
			if(count>floor) {
				return nums[floor];
			}
		}
		return 0;
    }
}

方法2

分析:将数组元素放入Map<Integer,Integer>中,重复的value+1.时间复杂度O(n)

class Solution {
    public int majorityElement(int[] nums) {
        		 //Map<数组元素,出现次数>
		Map<Integer,Integer> map=new HashMap<>();
		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);
			}
		}
		int floor=(int)Math.floor(nums.length/2);
		for(Map.Entry<Integer, Integer> s:map.entrySet()) {
			if(s.getValue()>floor) {
				System.out.println(s.getKey());
				return s.getKey();
			}
		}
		return 0;
    }
}

方法3

分析:摩尔投票法,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素则可能为目标元素。

class Solution {
    public int majorityElement(int[] nums) {
        int count  = 1;
        int maj = nums[0];
        for(int i = 1; i <nums.length; i++)
        {
            if(nums[i] == maj) 
                count++;
            else{
                count --;
                if(count == 0)
                {
                   maj = nums[i];
                   count = 1;
                }
            }  
        }
        return maj;   
        }
}

 

转载于:https://my.oschina.net/u/4035025/blog/3008504

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值