题解 | #数组中出现次数超过一半的数字#

数组中出现次数超过一半的数字

http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

栈顶是相同元素就入栈,栈顶是不同元素就出栈。最后栈里剩下的就是出现超过一半的那个元素。

import java.util.Stack;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        Stack<Integer> stack = new Stack<>();
        for(int i=0; i<array.length; i++){
            if(stack.isEmpty()){
                stack.push(array[i]);
            }else{
                int st = stack.get(stack.size()-1);
                if(st == array[i])
                    stack.push(array[i]);
                else
                    stack.pop();
            }
        }
        return stack.pop();
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
被加薪的哈里很优秀:应该继续招人,不会给你留岗位的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务