import java.util.*; public class Main{ public static void main(String[] args) { int[] nums = {6, 1, 5, 3, 1, 1, 2, 2, 2, 2, 1, 3, 3, 4, 4, 4, 5, 5, 5}; delSameNum(nums); } public static void delSameNum(int[] nums) { if (nums == null || nums.length == 0) return; LinkedList<Integer> stack = new LinkedList<>(); int count = 1; for(int i = 0; i < nums.length; i++) { if (!stack.isEmpty()) { if (stack.peek() == nums[i]) { stack.push(nums[i]); count++; if (i == nums.length - 1 && count >= 3) { while (count-- != 0) stack.pop(); } } else if ((stack.peek() != nums[i]) && count >= 3) { while (count-- != 0) stack.pop(); count = 1; if (stack.size() > 1) { int tmp = stack.pop(); if (tmp == stack.peek()) count++; stack.push(tmp); } if (!stack.isEmpty() && stack.peek() == nums[i]) { stack.push(nums[i]); count++; if (i == nums.length - 1 && count >= 3) { while (count-- != 0) stack.pop(); } } else { stack.push(nums[i]); } } else { count = 1; stack.push(nums[i]); } } else stack.push(nums[i]); } int[] arr = new int[stack.size()]; for (int i = arr.length - 1; i >= 0; i--) { arr[i] = stack.pop(); } for (int i : arr) { System.out.print(i + " "); } System.out.println(); } }