leetcode 496, 503, 556. Next Greater Element I, II, III | 496, 503, 556. 下一个更大元素 I,II,III(单调栈)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 496, 503, 556. Next Greater Element I, II, III | 496, 503, 556. 下一个更大元素 I,II,III(单调栈)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
496. Next Greater Element I
https://leetcode.com/problems/next-greater-element-i/
單調(diào)棧問(wèn)題,參考:https://leetcode.com/problems/next-greater-element-i/discuss/97595/Java-10-lines-linear-time-complexity-O(n)-with-explanation
503. Next Greater Element II
https://leetcode.com/problems/next-greater-element-ii/
class Solution {public int[] nextGreaterElements(int[] nums) {int[] result = new int[nums.length];Arrays.fill(result, -1);Stack<Integer> valueStack = new Stack<>();Stack<Integer> indexStack = new Stack<>();for (int i = 0; i < nums.length * 2 - 1; i++) {int index = i % nums.length; // circularlywhile (!valueStack.isEmpty() && valueStack.peek() < nums[index]) {result[indexStack.pop()] = nums[index];valueStack.pop();}valueStack.push(nums[index]);indexStack.push(index);}return result;} }556. Next Greater Element III
https://leetcode.com/problems/next-greater-element-iii/
總結(jié)
以上是生活随笔為你收集整理的leetcode 496, 503, 556. Next Greater Element I, II, III | 496, 503, 556. 下一个更大元素 I,II,III(单调栈)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode 497, 528. R
- 下一篇: leetcode 84. Largest