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.
Example 1:
Input: [3,2,3] Output: 3
Example 2:
Input: [2,2,1,1,1,2,2] Output: 2
class Solution { public int majorityElement(int[] nums) { Arrays.sort(nums); return(nums[nums.length/2]); } }
既然超过n/2次,那排序完成后肯定中间的element就是要求的。
class Solution { public int majorityElement(int[] nums) { // Arrays.sort(nums); // return(nums[nums.length/2]); int res = nums[0], count=1; for(int i =1; i < nums.length; i++){ if(nums[i] == res){ count++; } else{ count--; } if(count<=0) {res = nums[i]; count=1;} } return res; } }
摩尔投票法,先将第一个数字假设为众数,然后把计数器设为1,比较下一个数和此数是否相等,若相等则计数器加一,反之减一。然后看此时计数器的值,若为零,则将下一个值设为候选众数。以此类推直到遍历完整个数组,当前候选众数即为该数组的众数。
原理:超过半数的数一定能抵消掉所有别的数然后存活下来。
class Solution { public int majorityElement(int[] nums) { // Arrays.sort(nums); // return(nums[nums.length/2]); // int res = nums[0], count=1; // for(int i =1; i < nums.length; i++){ // if(nums[i] == res){ // count++; // } // else{ // count--; // } // if(count<=0) {res = nums[i]; // count=1;} // } // return res; Map<Integer, Integer> counts = new HashMap<Integer, Integer>(); for (int num : nums) { if (!counts.containsKey(num)) { counts.put(num, 1); } else { counts.put(num, counts.get(num)+1); } } for(Map.Entry<Integer,Integer> me : counts.entrySet()){ if(me.getValue() > nums.length/2) return me.getKey(); } return -1; } }
HashMap.