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

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();
    }
}