@@ -0,0 +1,1423 @@
+import java.util.Arrays;%0Aimport java.util.HashMap;%0Aimport java.util.Map;%0A%0A/**%0A * Given an array of size n, find the majority element.%0A * The majority element is the element that appears more than %E2%8C%8A n/2 %E2%8C%8B times.%0A * You may assume that the array is non-empty and the majority element%0A * always exist in the array.%0A * https://leetcode.com/problems/majority-element/%0A * Created by dgq on 16/7/19.%0A */%0Apublic class MajorityElement %7B%0A%09public int majorityElement(int%5B%5D nums) %7B%0A%09%09return sortWay(nums);%0A%09%7D%0A%0A%09/**%0A%09 * %E5%85%88%E5%B0%86%E6%95%B0%E7%BB%84%E6%8E%92%E5%BA%8F,%E6%97%A2%E7%84%B6%E9%A2%98%E7%9B%AE%E8%AF%B4%E4%BA%86%E8%82%AF%E5%AE%9A%E6%9C%89%E8%BF%99%E4%B9%88%E4%B8%AAmajority number,%0A%09 * %E9%82%A3%E4%B9%88%E5%9C%A8%E6%95%B0%E7%BB%84%E4%B8%AD%E9%97%B4%E7%9A%84%E5%BF%85%E5%AE%9A%E6%98%AF%E8%BF%99%E4%B8%AA%E6%95%B0%0A%09 * %E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6:O(nlogn)%0A%09 * @param nums%0A%09 * @return%0A%09 */%0A%09private int sortWay(int%5B%5D nums)%7B%0A%09%09Arrays.sort(nums);%0A%09%09return nums%5Bnums.length/2%5D;%0A%09%7D%0A%09/**%0A%09 * %E7%94%A8HashMap,%E6%AF%94%E8%BE%83%E7%AE%80%E5%8D%95%0A%09 * %E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6:O(n)%0A%09 * @param nums%0A%09 * @return%0A%09 */%0A%09private int hashMapWay(int%5B%5D nums)%7B%0A%09%09Map%3CInteger, Integer%3E map = new HashMap%3C%3E();%0A%09%09for (int num : nums)%7B%0A%09%09%09if (map.containsKey(num))%7B%0A%09%09%09%09int value = map.get(num);%0A%09%09%09%09map.put(num, value+1);%0A%09%09%09%7Delse %7B%0A%09%09%09%09map.put(num, 1);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09int time = 0;%0A%09%09int result = 0;%0A%09%09for (Map.Entry%3CInteger, Integer%3E entry : map.entrySet())%7B%0A%09%09%09if (entry.getValue() %3E= nums.length/2 && entry.getValue() %3E time)%7B%0A%09%09%09%09time = entry.getValue();%0A%09%09%09%09result = entry.getKey();%0A%09%09%09%7D%0A%09%09%7D%0A%09%09return result;%0A%09%7D%0A%0A%09public static void main(String%5B%5D args)%7B%0A%09%09int%5B%5D nums = %7B3,2,3,1%7D;%0A%09%09int result = new MajorityElement().majorityElement(nums);%0A%09%09System.out.println(result);%0A%09%7D%0A%7D%0A

完成 Majority Element