leetcode-Next Greater Element II

来源:互联网 发布:php增删改查源码下载 编辑:程序博客网 时间:2024/05/16 17:13

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);否则出错。

1 0
原创粉丝点击