您的位置:首页 > 其它

169. Majority Element

2016-11-25 22:45 197 查看
public static int majorityElement(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}

int count = 0;
int number = nums[0];
for(int i = 0; i < nums.length; i++) {
if(number == nums[i]) {
count++;
}else if(count == 0){
number = nums[i];
count++;
}else {
count--;
}
}
count = 0;
for(int i = 0; i < nums.length; i++) {
if(number == nums[i]) {
count++;
}
}
if(count >= (nums.length/2)) {
return number;
}else {
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: