標籤:
題目:Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
題意:找到數組中權重大於⌊ n/3 ⌋的數字(成為眾數)。
思路:
為了同時滿足時間複雜度和空間複雜度,不能用Map來做,根據題意,大於⌊ n/3 ⌋的數字最多不會超過兩個,
記變數n1, n2為候選眾數; c1, c2為它們對應的出現次數
遍曆數組,記當前數字為num
若num與n1或n2相同,則將其對應的出現次數加1
否則,若n1或n2為空白,則將其賦值為num,並將對應的計數器置為1
否則,將n1與n2中出現次數較少的數位計數器減1,若計數器減為0,則將其賦值為num,並將對應的計數器置為1
最後,再統計一次候選眾數在數組中出現的次數,若滿足要求,則返回之。
代碼:
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> list = new ArrayList<Integer>(); if(nums == null || nums.length == 0) return list; int n = nums.length; int count = n/3; int num1 = nums[0]; int num2 = nums[0]; int count1 = 1; int count2 = 0; for(int i = 1 ; i < n ; i++){ int temp = nums[i]; if(temp == num1){ count1++; }else if(temp == num2){ count2++; }else{ if(count2 == 0){ // 最開始 num2 = temp; count2 = 1; continue; } if(count1 < count2){ count1--; }else count2--; if(count1 == 0){ num1 = temp; count1 = 1; } if(count2 == 0){ num2 = temp; count2 = 1; } } } count1 = 0; count2 = 0; for(int i = 0 ; i < n ; i++){ if(nums[i] == num1) count1++; if(nums[i] == num2) count2++; } if(count1 > count) list.add(num1); if(num2 != num1 && count2 > count) list.add(num2); return list; }}
參考連結:http://www.tuicool.com/articles/eA7nIzY
[LeetCode-JAVA] Majority Element II