1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int[] secondGreaterElement(int[] nums) { int n = nums.length; int[] ans = new int[n]; Arrays.fill(ans, -1); int[][] arr = new int[n][2]; for (int i = 0; i < n; ++i) { arr[i] = new int[]{nums[i], i}; } Arrays.sort(arr, (a, b) -> b[0] - a[0]); TreeSet<Integer> ts = new TreeSet<>(); for (int[] p : arr) { int i = p[1]; Integer j = ts.higher(i); if (j != null && ts.higher(j) != null) { ans[i] = nums[ts.higher(j)]; } ts.add(i); } return ans; } }
|