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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题目解析:
我用了Hashmap的方法, 感觉不是最好的, 但是是最好想到的. 如果有更好方法的童鞋们求评论我~~么么哒~时间复杂度是O(2n), 也就是两次遍历, 但是有memory的限制, 就是开辟一个新的hash.
白板写的时候容易出错的就是hashmap的函数, keySet()啊, containsKey啊~之类的~
1 public int majorityElement(int[] num) { 2 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 3 4 for(int i = 0; i < num.length; i++){ 5 if(map.containsKey(num[i])) 6 map.put(num[i], map.get(num[i]) + 1); 7 else 8 map.put(num[i], 1); 9 } 10 for(int j: map.keySet()){ 11 int value = map.get(j); 12 if(value > num.length / 2) 13 return j; 14 } 15 return -1; 16 }