数组中次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
1 class Solution { 2 public int majorityElement(int[] nums) { 3 if(nums.length == 1){ 4 return nums[0]; 5 } 6 Map<Integer,Integer> map = new HashMap<>(); 7 int length = nums.length/2; 8 for(int i : nums){ 9 if(map.containsKey(i)){ 10 int count = map.get(i)+1; 11 map.put(i,count); 12 if(count > length){ 13 return i; 14 } 15 }else{ 16 map.put(i,1); 17 } 18 } 19 return -1; 20 } 21 }

浙公网安备 33010602011771号