描述:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:
1.就本题来说,最容易想到的思路就是遍历元素的同时用一个map来存储该元素和该元素出现的次数,如果包含还元素则相应的count+1,如果不包含,则put(num,1),即可
2.但HashMap中存储的key和value都是Integer,每次对value加1时要面临相应的拆箱和装箱操作,即创建了大量的对象,对堆内存是个不小的开始。其实可以将count变量设置成一个int[]数组形式,每次遍历时如果包含该元素,则map.get(key)[0]++;即可,第一次出现的话,int arr[]=new int[1];arr[0]=1;map.put(key,arr);每个key仅需要创建一个对象即可。
3.如果让统计该数组出现最多次数的元素用思路2是可以的,而本题要求的是出现次数大于一半长度的元素,这个大于一半长度的条件要好好考虑一下。仔细想想,其实出现的长度大于一半,也就是说别的元素出现的次数的总和还没有一个元素出现的次数多,所以将次数抵消一下,最后剩余的元素肯定是出现次数大于一般长度的元素。废话就不说了,直接上代码。
代码:
public int majorityElement(int[] nums) { if(nums==null||nums.length==0) return Integer.MIN_VALUE; int majorityNum=0,count=0; for(int i=0;i<nums.length;i++) { if(count==0) { majorityNum=nums[i]; count=1; }else { if(majorityNum==nums[i]) count++; else count--; } } return majorityNum; }