publicintpeek(){ if (queue.isEmpty()) { thrownew RuntimeException("Stack is empty!"); } while (queue.size() != 1) { help.add(queue.poll()); } int res = queue.poll(); help.add(res); swap(); return res; }
publicintpop(){ if (queue.isEmpty()) { thrownew RuntimeException("Stack is empty!"); } while (queue.size() > 1) { help.add(queue.poll()); } int res = queue.poll(); swap(); return res; }
当有元素重复时,栈中不能单单只存储一个 Integer 类型变量,而应该存储一个 ArrayList,将相同值的元素存储到同一个 List 中。
算法整体顺序一致,区别在于弹栈时弹出的是一个 List,需要将这个 List 中的所有元素都遍历一次,加入到 res[][] 中;另外,在获取左侧的元素索引值时,需要获取到栈顶第二个 List 里的最后一个元素(这个元素是最靠近当前弹出栈的元素的,因为整体是单调的,越靠后的,越在 List 的后面)。
// for test publicstaticint[] getRandomArrayNoRepeat(int size) { int[] arr = newint[(int) (Math.random() * size) + 1]; for (int i = 0; i < arr.length; i++) { arr[i] = i; } for (int i = 0; i < arr.length; i++) { int swapIndex = (int) (Math.random() * arr.length); int tmp = arr[swapIndex]; arr[swapIndex] = arr[i]; arr[i] = tmp; } return arr; }
// for test publicstaticint[] getRandomArray(int size, int max) { int[] arr = newint[(int) (Math.random() * size) + 1]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * max) - (int) (Math.random() * max); } return arr; }
// for test publicstaticint[][] rightWay(int[] arr) { int[][] res = newint[arr.length][2]; for (int i = 0; i < arr.length; i++) { int leftLessIndex = -1; int rightLessIndex = -1; int cur = i - 1; while (cur >= 0) { if (arr[cur] < arr[i]) { leftLessIndex = cur; break; } cur--; } cur = i + 1; while (cur < arr.length) { if (arr[cur] < arr[i]) { rightLessIndex = cur; break; } cur++; } res[i][0] = leftLessIndex; res[i][1] = rightLessIndex; } return res; }
// for test publicstaticbooleanisEqual(int[][] res1, int[][] res2){ if (res1.length != res2.length) { returnfalse; } for (int i = 0; i < res1.length; i++) { if (res1[i][0] != res2[i][0] || res1[i][1] != res2[i][1]) { returnfalse; } }
returntrue; }
// for test publicstaticvoidprintArray(int[] arr){ for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); }
publicstaticvoidmain(String[] args){ int size = 10; int max = 20; int testTimes = 2000000; for (int i = 0; i < testTimes; i++) { int[] arr1 = getRandomArrayNoRepeat(size); int[] arr2 = getRandomArray(size, max); if (!isEqual(getNearLessNoRepeat(arr1), rightWay(arr1))) { System.out.println("Oops!"); printArray(arr1); break; } if (!isEqual(getNearLess(arr2), rightWay(arr2))) { System.out.println("Oops!"); printArray(arr2); break; } } } }