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.
public class Solution {
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
}
本文介绍了一个简单的多数元素查找算法,该算法能在O(n)时间内找到数组中出现次数超过n/2的元素。通过迭代数组并使用计数方式跟踪当前候选元素,最终返回出现次数最多的那个元素。
2728

被折叠的 条评论
为什么被折叠?



