LeetCode[169] Majority Element
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.
投票法
复杂度
O(N),O(1)
思路
设定一个candidate,和这个candidate对应的count.如果一个数和这个candidate相等,那么就将count增加,否则减少count的数目。
代码
public int majorityElement(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int candidate = 0;
int cnt = 0;
for(int num : nums) {
if(num == candidate) {
cnt ++;
}
else if(cnt == 0) {
candidate = num;
}
else {
cnt --;
}
}
return candidate;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。