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

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

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();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务