您的位置:首页 > 其它

lintcode-medium-Majority Number II

2016-03-29 18:04 330 查看
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.

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) {
// write your code

if(nums == null || nums.size() == 0)
return 0;

Integer num1 = null;
Integer num2 = null;
int count1 = 0;
int count2 = 0;

for(int i = 0; i < nums.size(); i++){
int temp = nums.get(i);

if(num1 == null){
num1 = temp;
count1 = 1;
}
else if(num1 == temp){
count1++;
}
else if(num2 == null){
num2 = temp;
count2 = 1;
}
else if(num2 == temp){
count2++;
}
else{
count1--;
count2--;
if(count1 == 0){
num1 = temp;
count1 = 1;
}
if(count2 == 0){
num2 = temp;
count2 = 1;
}
}
}

count1 = 0;
count2 = 0;

for(int i = 0; i < nums.size(); i++){
if(num1 == nums.get(i))
count1++;
if(num2 == nums.get(i))
count2++;
}

if(count1 > nums.size() / 3)
return num1;

return num2;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: