标签:
题目:
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/
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4645611.html