剑指 Offer 39. 数组中出现次数超过一半的数字
题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2
限制:
1 <= 数组长度 <= 50000
代码:
//摩尔投票法 ,只要和基数值相同就+1,不同-1,最坏情况相同和不同紧邻而排,这样最后的cur也应一定是正确的
1 class Solution { 2 public int majorityElement(int[] nums) { 3 int count=0; 4 int cur=0; 5 for(int num:nums){ 6 if(count==0){cur=num;count++;} 7 else{count+=(cur==num?1:-1);} 8 } 9 return cur; 10 } 11 }
代码2:
//利用数组排序,则中间的元素必是所求元素
1 class Solution { 2 public int majorityElement(int[] nums) { 3 Arrays.sort(nums); 4 return nums[nums.length/2]; 5 } 6 }
代码3:
//利用HashMap
1 class Solution { 2 public int majorityElement(int[] nums) { 3 Map<Integer,Integer> map=new HashMap<>(); 4 for (int i = 0; i < nums.length; i++) { 5 int count=map.getOrDefault(nums[i],0)+1; 6 if(count>nums.length/2){return nums[i];} 7 map.put(nums[i],count); 8 } 9 return 0; 10 } 11 }