贴个算法,大佬们看是否有错,这两个用例是能过的 public static void main(String[] args) { //int[] nums = new int[]{2, 1, 1, 2,2,1,4,4,4};//1 int[] nums = new int[]{2, 1, 2, 2, 1, 4, 4, 4};//2 Deque<Integer> st = new ArrayDeque<>(); int pre = -1; for(int x : nums) { if(pre == x) continue; if(st.isEmpty() || st.peek() != x) { st.push(x); } else { while(!st.isEmpty() &amp;&amp; st.peek() == x) { st.pop(); } pre = x; } } while(!st.isEmpty()) { System.out.println(st.pollFirst()); } }