LeetCode第169题

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

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

示例 1:

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

示例 2:

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

思路:1.将整形数组中的元素存到hashmap中,键为数组中的值,值为出现的次数

           2.对hashmap进行遍历,将键值对的值中大于n/2的数给取出来

public int majorityElement(int[] nums){
		//思路:将整形数组中的元素存到hashmap中,键为数组中的值,值为出现的次数
		Map<Integer,Integer> map=new HashMap<>();
		int count=0;
		int result=0;
		for(int i=0;i<nums.length;i++){
			if(!map.containsKey(nums[i])){
				map.put(nums[i], 1);
			}
			else{
				count=map.get(nums[i]);
				count+=1;
				map.put(nums[i], count);
			}
		}
		//对hashmap进行遍历,将键值对的值中大于n/2的数给取出来
		for(Map.Entry<Integer, Integer> Entry:map.entrySet()){
			if(Entry.getValue()>nums.length/2){
				result=Entry.getKey();
			}
		}
	
		return result;
	}

猜你喜欢

转载自blog.csdn.net/qq_37764098/article/details/84559833