[Leetcode Java] Majority Element, leetcodemajority
The questions are as follows:
Given an array of size n, find the majority element. The majority element is the element that appears more⌊ n/2 ⌋Times.
You may assume that the array is non-empty and the majority element always exist in the array.
Solution 1 is as follows: a more common solution is also stupid
public class Solution { public int majorityElement(int[] num) { HashMap<Integer,Integer> map=new HashMap<>(); for(int a:num){ if(map.get(a)!=null){ int i=map.get(a); map.put(a,i+1); } else{ map.put(a,1); } } List<Map.Entry<Integer,Integer>> list =new ArrayList<>(); list.addAll(map.entrySet()); Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){ public int compare(Map.Entry<Integer,Integer> m1,Map.Entry<Integer,Integer> m2){ return m2.getValue()-m1.getValue(); } }); return list.get(0).getKey(); }}
The second solution is as follows: Make full use of the conditions given in the question
public class Solution { public int majorityElement(int[] num) { HashMap<Integer,Integer> map=new HashMap<>(); for(int a:num){ if(map.get(a)!=null){ int i=map.get(a); map.put(a,i+1); } else{ map.put(a,1); } } for(Map.Entry<Integer,Integer> m:map.entrySet()){ if(m.getValue()>num.length/2){ return m.getKey(); } } return 0; }}The third solution is my search on the Internet: I feel tired after reading it ..
public class Solution { public int majorityElement(int[] num) { Arrays.sort(num); return num[num.length/2]; }}WTF ....