503. Next Greater Element II

Photo by Daniel Seßler on Unsplash
Photo by Daniel Seßler on Unsplash
此題要我們找 nums 中,每個數字的下一個較大的數字。我們可以用 decreasing monotonic stack 來解。

Problem

Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.

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, return -1 for this number.

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [1,2,3,4,3]
Output: [2,3,4,-1,4]

Constraints:

  • 1 <= nums.length <= 104
  • -109 <= nums[i] <= 109

Solution

此題要我們找 nums 中,每個數字的下一個較大的數字。我們可以用 decreasing monotonic stack 來解。題目提到 nums 是循環的,因此我們可以將 nums 延伸一倍,這樣可以簡化循環的處理。因為我們是找右邊下一個較大的數字,所以我們要從後面往前面來建立 decreasing monotonic stack。當要 push 數字進去 stack 之前,stack 最後的數字就是下一個較大的數字。若 stack 是空的時候,那表示沒有較大的數字,因此值會是 -1。

Monotonic Stack

  • Time: O(n)
  • Space: O(n)
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        LinkedList<Integer> stack = new LinkedList<>();
        int[] results = new int[n];

        for (int i = n * 2 - 1; i >= 0; i--) {
            while (!stack.isEmpty() && stack.peek() <= nums[i % n]) {
                stack.pop();
            }

            results[i % n] = stack.isEmpty() ? -1 : stack.peek();

            stack.push(nums[i % n]);
        }

        return results;
    }
}

參考

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

You May Also Like
Photo by Oladimeji Odunsi on Unsplash
Read More

72. Edit Distance

在解此題時,我們要先觀察 word1 如何變成 word2。以 Example1 為例,左下圖列出 “horse” 轉變成 “ros” 的 distance。表中,縱軸表示 “horse”,而橫軸表示 “ros”。
Read More
Photo by Diana Parkhouse on Unsplash
Read More

1048. Longest String Chain

此題中,wordA 是 wordB 的 predecessor 指只要插入一個 letter 到 wordA,那就會使得它和 wordB 一樣。然而,插入一個 letter 到一個地方,就要考慮 26 種字母。這使得整體的複雜度上升。
Read More
Photo by Bogdan Farca on Unsplash
Read More

39. Combination Sum

此題要我們列出所有可能的組合,所以我們可能用 backtracking 來找。但是,我們必須避免找到相同的組合。當兩個組合裡的數字和個數都依一樣,但順序不一樣時,他們依然是相同的組合。
Read More