503. Next Greater Element II
package LeetCode_503 import java.util.* /** * 503. Next Greater Element II * https://leetcode.com/problems/next-greater-element-ii/description/ * * 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. * */ class Solution { /** * solution 1: brute force, Time complexity:O(n*n), Space complexity:O(n) * solution 2: monotonic stack, Time complexity:O(n), Space complexity:O(n) * */ fun nextGreaterElements(nums: IntArray): IntArray { val n = nums.size val result = IntArray(n, { -1 }) //solution 1 /*for (i in nums.indices) { //because need loop through array, we use j%n for (j in i + 1 until (i + n)) { if (nums[j % n] > nums[i]) { result.set(i, nums[j % n]) break } } }*/ //solution 2, store indices of monotonically increasing element val stack = Stack<Int>() for (i in 0 until 2 * n) { //because need loop through array, we use j%n val num = nums[i % n] while (stack.isNotEmpty() && nums[stack.peek()] < num) { result.set(stack.pop(),num) } //need care about the index if (i<n) { stack.push(i) } } return result } }
标签:
monotonic stack
, leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)