public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int voted = 1;
int res = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] == res) {
voted++;
} else {
voted--;
if (voted == 0) {
res = array[i];
voted++;
}
}
}
return res;
}
}
数组中出现次数超过一半的数字
最新推荐文章于 2025-12-17 19:02:04 发布
这段代码实现了一个查找数组中出现次数超过一半的元素的算法。它使用了投票策略,遍历数组,当遇到相同元素时增加计数,不同则减少,当计数为0时更新目标元素。
687

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



