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.
Leetcode的官方答案给的解答很好,我的方法是HashMap. 除了brute force和sorting常见方法以外,还有几个方法,思路都还不错,1是我的方法,我觉得2、4、5都是不错的思路。
1 public class Solution { 2 public int majorityElement(int[] num) { 3 int n = num.length; 4 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 5 for (int elem : num) { 6 if (map.containsKey(elem)) { 7 map.put(elem, map.get(elem)+1); 8 } 9 else {10 map.put(elem, 1);11 }12 }13 for (int item : map.keySet()) {14 if (map.get(item) > n/2) {15 return item;16 }17 }18 return -1;19 }20 }
新闻热点
疑难解答