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.輸入一個大小爲n的數組,整個數組裏面將會含有一個衆數,即這個元素出現的次數大於n/2,咱們須要找到並返回這個衆數數組
//HashMap實現 時間複雜度O(n) public int majorityElement(int[] nums) { HashMap<Integer, Integer> count = new HashMap<Integer, Integer>(); int length = nums.length; if(length<=1){ return nums[0]; } for(int i=0;i<length;i++){ if(count.get(nums[i]) != null){ int temp = count.get(nums[i]); count.put(nums[i],temp+1); if(temp+1 > length/2){ return nums[i]; } }else{ count.put(nums[i], 1); } } return -1; }
//思想:對於一個排序好的數組,第n/2的位置的元素必定是存在的這個衆數 public int majorityElement(int[] nums) { Arrays.sort(nums); return nums[nums.length/2]; }
public int majorityElement(int[] nums) { int res = nums[0]; int count = 1; for(int i=1;i<nums.length;i++){ if(nums[i] == res) count ++; else if(count >1) count --; else res = nums[i]; } return res; }