LeetCode503《Next Greater Element II》栈的应用

来源:互联网 发布:西瓜皮手表软件下载 编辑:程序博客网 时间:2024/06/04 00:59
LeetCode503《Next Greater Element II》----栈的应用

题目如下(来源LeetCode.503):
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.
样例:
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.

大意是给定一个序列,Print出每个元素在序列中下一个比他大的元素(队末元素的下一个是队头元素)。如果没有比它大的元素,则输出-1。

最容易想到的算法是直接对每个元素,循环一遍序列,当找到一个比它要大的元素时就停止循环,输出这个元素,若在循环后仍未找到则输出-1。

vector<int> nextGreaterElements(vector<int>& nums) {        vector<int> result;        int size = nums.size();        int j;        for(int i = 0;i < size;i++){            j = (i + 1) % size;            while(i != j && nums[i] >= nums[j]){                j = (j + 1) % size;            }            if(i == j)result.push_back(-1);            else result.push_back(nums[j]);        }        return result;    }

但是这种方法的坏处显而易见,每个元素都循环一遍,程序的运行时间会很长。

我们的目的只需要寻找到下一个比它大的元素即可。创建一个栈(存下标),从头依次遍历一遍序列中的元素,将它的下标加入栈中,在遍历的过程中,对当前元素,若它比栈里的下标对应元素要大,则result里对应的元素就填写为这个比它大的元素,然后pop掉这个下标,一次循环下来,栈中剩下的就是没有找到比它大的元素的元素下标。所以需要从0开始看有没有比它大的元素,这次遍历的过程与第一次一样,只是这次不用在栈里添加下标。

代码如下

vector<int> nextGreaterElements(vector<int>& nums) {        int size = nums.size();        vector<int> result(size,-1);        stack<int> s;        for(int i = 0; i < 2 * size - 1; i++){            int num = nums[i % size];            while(!s.empty() && num > nums[s.top()]){                result[s.top()] = num;                s.pop();            }            if(i < size)s.push(i);        }        return result;    }

这样的方法,由于只遍历了两次元素序列,直接将时间复杂度从一开始的O(n^2)变成了O(n)。

0 0
原创粉丝点击