public class DayCode { public static void main(String[] args) { int[] nums = new int[]{1, 2, 1}; int[] ans = new DayCode().nextGreaterElements(nums); System.out.println("ans is " + Arrays.toString(ans)); }
/** * 链接:https://leetcode-cn.com/problems/next-greater-element-ii * 时间复杂度O(n * n) * 空间复杂度O(n) * @param nums * @return */ public int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] ans = new int[n];
int[] tempNums = new int[2 * n]; for (int i = 0; i < n; i++) { tempNums[i] = nums[i]; tempNums[n + i] = nums[i]; }
Map<Integer, Integer> map = new HashMap<>(n); for (int i = 0; i < n; i++) { for (int j = i + 1; j < 2 * n && j < n + i; j++) { if (tempNums[j] > tempNums[i]) { map.put(i, tempNums[j]); break; } } }
for (int i = 0; i < n; i++) { ans[i] = map.getOrDefault(i, -1); } return ans; }}
评论