Share 496. next greater element ii c++,

goldencat467

New member
#496, #next phần tử lớn hơn II, #C ++, #LeetCode
## 496. Phần tử lớn hơn tiếp theo II (C ++)

Đưa ra một mảng `nums` của các số nguyên, hãy trả về một mảng` câu trả lời 'sao cho' câu trả lời `là số nguyên nhỏ nhất lớn hơn` nums `xuất hiện trong mảng hoặc` -1`Số nguyên như vậy.

**Ví dụ 1:**

`` `
Đầu vào: nums = [4,1,2]
Đầu ra: [5,2,3]
`` `

** Ví dụ 2: **

`` `
Đầu vào: nums = [4,1,2,1]
Đầu ra: [5,2,3, -1]
`` `

**Hạn chế:**

* `1 <= nums.length <= 10^5`
* `0 <= nums <= 10^9`

**Giải pháp:**

`` `C ++
Giải pháp lớp {
công cộng:
Vector <Int> NextGreaterErements (Vector <Int> & nums) {
int n = nums.size ();
Vector <Int> res (n, -1);
ngăn xếp <Int> st;
for (int i = 2 * n-1; i> = 0; i--) {
while (! St.empty () && nums [St.Top ()] <= nums [i % n]) {
St.Pop ();
}
res [i % n] = St.Empty ()?-1: nums [St.Top ()];
St.Push (i % n);
}
trả lại res;
}
};
`` `

## hashtags

* #496
* #next yếu tố lớn hơn II
* #C ++
* #LeetCode
=======================================
#496, #next Greater Element II, #C++, #LeetCode
## 496. Next Greater Element II (C++)

Given an array `nums` of integers, return an array `answer` such that `answer` is the smallest integer greater than `nums` that appears in the array, or `-1` if there is no such integer.

**Example 1:**

```
Input: nums = [4,1,2]
Output: [5,2,3]
```

**Example 2:**

```
Input: nums = [4,1,2,1]
Output: [5,2,3,-1]
```

**Constraints:**

* `1 <= nums.length <= 10^5`
* `0 <= nums <= 10^9`

**Solution:**

```c++
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> res(n, -1);
stack<int> st;
for (int i = 2 * n - 1; i >= 0; i--) {
while (!st.empty() && nums[st.top()] <= nums[i % n]) {
st.pop();
}
res[i % n] = st.empty() ? -1 : nums[st.top()];
st.push(i % n);
}
return res;
}
};
```

## Hashtags

* #496
* #next Greater Element II
* #C++
* #LeetCode
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top