LeetCode 503. Next Greater Element II

本文解决LeetCode中的下一个更大元素II问题,针对循环数组的特点,介绍了一种通过双倍遍历来寻找每个元素的下一个更大元素的方法,并给出了Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/next-greater-element-ii/

题目:

Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.

Example 1:

Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.

Note: The length of given array won't exceed 10000.

题解:

Next Greater Element I进阶版.

一般这类带环的一种常见做法是加长一倍. 这里就是把nums 走两边.

 没用HashMap<Integer, Integer>是因为nums里会有duplicate. 这里的Stack<Integer> stk 存的是element index 而不是element, 需要index来填res.

Time Complexity: O(n), n = nums.length.

Space: O(n), res size.

AC Java:

 1 class Solution {
 2     public int[] nextGreaterElements(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return nums;
 5         }
 6         
 7         int len = nums.length;
 8         int [] res = new int[len];
 9         Stack<Integer> stk = new Stack<Integer>();
10         
11         for(int i = len*2-1; i>=0; i--){
12             int index = i%len;
13             while(!stk.isEmpty() && nums[index]>=nums[stk.peek()]){
14                 stk.pop();
15             }
16             
17             if(i<len){
18                 res[index] = stk.isEmpty() ? -1 : nums[stk.peek()];        
19             }
20             
21             stk.push(index);
22         }
23         
24         return res;
25     }
26 }

 跟上Next Greater Element III.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/6637862.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值