您的位置:首页 > 其它

169. Majority Element

2016-08-23 16:27 162 查看
Given an array of size n, find the majority element. The majority element is the element that appears
more than
⌊ n/2 ⌋
times.

You may assume that the array is non-empty and the majority element always exist in the array.

思路:

因为一定存在Majority Element,所以Majority Element的个数减去其他所有数字的个数一定大于0

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