leetcode-Next Greater Element II

Question:
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.

Solution:

解法1:

也就是暴力解法,判斷條件 j != i; j = (j+1)%len,
沒什麼可說的,不過也可以通過

解法2:

使用棧解決

class Solution {
public:
    vector<int> nextGreaterElements(vector<int>& nums) {
        if(nums.empty()){
            return nums;
        }
        int len = nums.size();
        vector<int> res(len);
        int stack[len];
        int top = -1;
        stack[++top] = 0;//棧存儲的索引
        for(int i = 1 ; i< len ;i++){//第一遍棧中留下的非增序列(由下到上非增)
            while(top>=0 && nums[i] > nums[stack[top]]){
                res[stack[top--]] = nums[i];
            }
            stack[++top] = i;
        }
        for(int i = 0 ; i <= stack[0] ; i++){//第二遍查找棧頂的nextrGeate,查找範圍0-stack[0],stack[0]爲最大值索引
            while(top>=0 && nums[i] > nums[stack[top]]){
                res[stack[top--]] = nums[i];
            }
        }
        while(top >= 0 ){//第三遍將剩下的沒有nextGreate的置爲-1
            res[stack[top--]] = -1;
        }
        return res;
    }
};

總結:剛開始總是嘗試將nums中的值存入棧中,走了不少彎路,以後切記不止值可以代表元素,索引也可以代表元素;還有vector是可以通過[]
符號賦值的,以前只知道push_back;當使用[] 賦值時,vector變量聲明需要指定元素個數:vector res(len);否則出錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章