LeetCode刷題169. Majority Element
阿新 • • 發佈:2018-12-13
題目描述: 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
解題思路:找到陣列中出現次數大於⌊ n/2 ⌋的元素,也就是說要統計一下陣列中各元素出現的次數。我最先想到的方法就是利用一個HashMap<K,V>來計數,Key為陣列中的元素,Value為出現次數,完成以後對HashMap遍歷一次就可以輕鬆得到答案。 程式碼如下:
class Solution { public int majorityElement(int[] nums) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(nums[i])){ map.put(nums[i],map.get(nums[i])+1); }else{ map.put(nums[i],1); } } for(Integer key : map.keySet()){ if(map.get(key) > nums.length/2){ return (int)key; } } return 0; } }
分析:這個解法的時間複雜度O(n),空間複雜度O(n)。看了下談論中各位大佬的方法,其中支援最高的方法在空間複雜度上提高到O(1),程式碼如下,學習一番。
public class Solution { public int majorityElement(int[] num) { int major=num[0], count = 1; for(int i=1; i<num.length;i++){ if(count==0){ count++; major=num[i]; }else if(major==num[i]){ count++; }else count--; } return major; } }