给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的三分之一。
注意事项
数组中只有唯一的主元素
样例
给出数组[1,2,1,2,1,3,3] 返回 1
挑战
要求时间复杂度为O(n),空间复杂度为O(1)。
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
Notice
There is only one majority number in the array.
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Challenge
O(n) time and O(1) extra space.
思路:同时消除三个不一致的数
参考:http://www.cnblogs.com/theskulls/p/4915270.html
public class Solution {
/**
* @param nums: A list of integers
* @return: The majority number that occurs more than 1/3
*/
public int majorityNumber(ArrayList<Integer> nums) {
if(nums == null || nums.size() == 0) return 0;
int candi1 = Integer.MIN_VALUE, count1 = 0;
int candi2 = Integer.MIN_VALUE, count2 = 0;
for(int i = 0; i < nums.size(); i++) {
int temp = nums.get(i);
if(temp != candi1 && temp != candi2) {
if(count1 == 0) {
candi1 = temp; count1++;
}else if(count2 == 0) {
candi2 = temp; count2++;
}else{
count1--;count2--;
}
}else if(temp == candi1) {
count1++;
}else{
count2++;
}
}
count1 = 0; count2 = 0;
for(int i = 0; i < nums.size(); i++) {
if(candi1 == nums.get(i))
count1++;
else if(candi2 == nums.get(i))
count2++;
}
return count1 > count2 ? candi1 : candi2;
}
}