hl同学问我一道这个题,想了一种方法,感觉还是不错的,只扫描一次,贴一下伪代码:
int more_than_half(int a[],int n){
stack<int> st;
for(int i = 1; i < n; i++){
if(st.empty()){
st.push(a[i]);
}else{
if(a[i] != st.top()){
st.pop();
}else{
st.push(a[i]);
}
}
}
return st.top();
}
思想是不同的数相互抵消,最终剩的数就是超过一半的。
按照这种思想,计数的方法来实现:
int more_than_half(int a[],int n){
int count,i;
int res;
for(i = count = 0; i < n; i++){
if(count == 0){
res = a[i];
count = 1;
}else{
if(res == a[i])
count++;
else
count--;
}
}
return res;
}
本文介绍了一种高效查找数组中出现次数超过一半的元素的算法。通过巧妙地利用数的抵消特性,该算法仅需遍历一次数组即可找出目标元素。文中给出了两种实现方式的伪代码。
1633

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



