[CTCI] 下一个较大元素

下一个较大元素

题目描述

现在我们有一个int数组,请你找出数组中每个元素的下一个比它大的元素。

给定一个int数组A及数组的大小n,请返回一个int数组,代表每个元素比他大的下一个元素,若不存在则为-1。保证数组中元素均为正整数。

测试样例:
[11,13,10,5,12,21,3],7
返回:[13,21,12,12,21,-1,-1]

单调栈!
 1 class NextElement {
 2 public:
 3     vector<int> findNext(vector<int> A, int n) {
 4         // write code here
 5         vector<int> res(n);
 6         stack<int> stk;
 7         for (int i = 0; i < n; ++i) {
 8             while (!stk.empty() && A[i] > A[stk.top()]) {
 9                 res[stk.top()] = A[i];
10                 stk.pop();
11             } 
12             stk.push(i);
13         }
14         while (!stk.empty()) {
15             res[stk.top()] = -1;
16             stk.pop();
17         }
18         return res;
19     }
20 };

下一个较大元素II

题目描述

现在有一个数组,请找出数组中每个元素的后面比它大的最小的元素,若不存在则为-1。

给定一个int数组A及数组的大小n,请返回每个元素所求的值组成的数组。保证A中元素为正整数,且n小于等于1000。

测试样例:
[11,13,10,5,12,21,3],7
[12,21,12,12,21,-1,-1]

BST!
 1 class NextElement {
 2 public:
 3     vector<int> findNext(vector<int> A, int n) {
 4         // write code here
 5         vector<int> res(n);
 6         set<int> st;
 7         for (int i = n - 1; i >= 0; --i) {
 8             auto it = st.lower_bound(A[i]);
 9             if (it == st.end()) {
10                 res[i] = -1;
11             } else if (*it != A[i]) {
12                 res[i] = *it;
13             } else {
14                 ++it;
15                 if (it == st.end()) res[i] = -1;
16                 else res[i] = *it;
17             }
18             st.insert(A[i]);
19         }
20         return res;
21     }
22 };
原文地址:https://www.cnblogs.com/easonliu/p/4678710.html