zoukankan      html  css  js  c++  java
  • 503. Next Greater Element II

    503. Next Greater Element II
    Medium

    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.

    Note: The length of given array won't exceed 10000.

     1 class Solution {
     2 public:
     3     vector<int> nextGreaterElements(vector<int>& nums) {
     4         vector<int> res(nums.size(),-1);
     5         stack<int> s;
     6         int n=nums.size();
     7         for(int i=0;i<n*2;++i)
     8         {
     9             int num=nums[i%n];
    10             while(!s.empty()&&nums[s.top()]<num)
    11             {
    12                 res[s.top()]=num;
    13                 s.pop();
    14             }
    15             if(i<nums.size())s.push(i);
    16         }
    17         return res;
    18     }
    19 };

    暴力可以accept, 不过太慢. 空间O(1) 时间 O(n2)

    这题使用stack结构是非常完美的, 根据数组的排放顺序, 空间O(1) ~ O(n)  时间O(n)

  • 相关阅读:
    POJ 1731
    POJ 1256
    POJ:1833 按字典序找到下一个排列:
    git工作流
    git 分之合并和冲突解决
    iis 7 操作 .net
    IIS7.0 Appcmd 命令详解
    SQL的注入式攻击方式和避免方法
    实例详解Django的 select_related
    django-ajax之post方式
  • 原文地址:https://www.cnblogs.com/lychnis/p/11299254.html
Copyright © 2011-2022 走看看