標籤:
題目:
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.
解題思路:
與Majority Elements不同是這裡需要維護兩個變數n1和n2,如果下一個數與這兩個數都不同的時候,count1和count2都減一,如果下一個數與n1或者n2相等的時候,對應的count++。最後的結果必定在n1或者n2中。
代碼:
1 public class Solution { 2 public int majorityNumber(ArrayList<Integer> nums) { 3 int n1 = nums.get(0), count1 = 1; 4 int index = 1; 5 for (; index < nums.size() && nums.get(index) == n1; index++) { 6 count1++; 7 } 8 if (index == nums.size()) { 9 return n1;10 }11 int n2 = nums.get(index), count2 = 1;12 for (int i = index + 1; i < nums.size(); i++) {13 if (nums.get(i) == n1) {14 count1++;15 } else if (nums.get(i) == n2) {16 count2++;17 } else {18 if (count1 == 0) {19 n1 = nums.get(i);20 count1 = 1;21 } else if (count2 == 0) {22 n2 = nums.get(i);23 count2 = 1;24 } else {25 count1--;26 count2--;27 }28 }29 }30 if (count1 == 0) {31 return n2;32 } else if(count2 == 0) {33 return n1;34 } else {35 int count = 0;36 for (int n : nums) {37 if (n == n1) {38 count++;39 }40 }41 if (count > nums.size()/3) {42 return n1;43 }44 return n2;45 }46 }47 }
reference:https://codesolutiony.wordpress.com/2015/03/15/lintcode-majority-element-ii/
[?]*Majority Element II