当前位置:网站首页>One brush 142 monotone stack next larger element II (m)
One brush 142 monotone stack next larger element II (m)
2022-07-03 16:57:00 【Tang and Song Dynasties】
subject :
Given a circular array ( The next element of the last element is the first element of the array ), Output the next larger element of each element .
Numbers x The next larger element of is in array traversal order , The first larger number after this number ,
This means that you should cycle through it to the next larger number . If it doesn't exist , The output -1.
-------------
Example :
Input : [1,2,1]
Output : [2,-1,2]
explain : first 1 The next larger number of is 2;
Numbers 2 Can't find the next larger number ;
the second 1 The next largest number of need to loop search , The result is also 2.
Be careful : The length of the input array will not exceed 10000.
---------------
reflection :
This question and 739. The daily temperature is almost the same .
At different times, this problem needs to cycle through the array .
I'm explaining the monotone stack 739. Daily temperature It's explained in detail in .
This article focuses on , How to deal with circular arrays .
I believe many students see this problem , Just like that, I directly splice the two arrays together , Then use the monotone stack to find the next maximum !
It can !
Talk about two nums Arrays are spliced together , Use the monotone stack to calculate the next maximum value of each element ,
Finally, the result set is result Array resize To the size of the original array .
The code is as follows :
// Version of a
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
// Splice a new nums
vector<int> nums1(nums.begin(), nums.end());
nums.insert(nums.end(), nums1.begin(), nums1.end());
// With the new nums Size to initialize result
vector<int> result(nums.size(), -1);
if (nums.size() == 0) return result;
// Start monotonous stack
stack<int> st;
for (int i = 0; i < nums.size(); i++) {
while (!st.empty() && nums[i] > nums[st.top()]) {
result[st.top()] = nums[i];
st.pop();
}
st.push(i);
}
// Finally, the result set is result Array resize To the original array size
result.resize(nums.size() / 2);
return result;
}
};
This kind of writing is really intuitive , But I did a lot of useless operations , For example, modified nums Array , And finally, I have to result Array resize Go back .
resize It doesn't take time , yes $O(1)$ The operation of , But expand nums The array is equivalent to one more $O(n)$ The operation of .
In fact, it can also be expanded nums, But in the process of traversal, the simulation goes on both sides nums.
The code is as follows :
// Version 2
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int> result(nums.size(), -1);
if (nums.size() == 0) return result;
stack<int> st;
for (int i = 0; i < nums.size() * 2; i++) {
// Simulate traversal on both sides nums, Note that they all use i % nums.size() To operate
while (!st.empty() && nums[i % nums.size()] > nums[st.top()]) {
result[st.top()] = nums[i % nums.size()];
st.pop();
}
st.push(i % nums.size());
}
return result;
}
};
Yes, version 2 not only simplifies the code , It also did less useless work than version 1 !
------------------------
Code :
class Solution {
public int[] nextGreaterElements(int[] nums) {
// Boundary judgment
if (nums == null || nums.length <= 1) return new int []{
-1};
int size = nums.length;
int[] result = new int[size];// Store results
Arrays.fill(result, -1);// initialization
Stack<Integer> stack = new Stack<>();// What's on the stack is nums Element subscript in
for (int i = 0; i < 2 * size; i++) {
while (!stack.isEmpty() && nums[i % size] > nums[stack.peek()]) {
result[stack.peek()] = nums[i % size]; // to update result
stack.pop();// Pop up the top of the stack
}
stack.push(i % size);
}
return result;
}
}
边栏推荐
- Preventing/catching “IllegalArgumentException: parameter must be a descendant of this view” error
- Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
- [combinatorics] polynomial theorem (polynomial theorem | polynomial theorem proof | polynomial theorem inference 1 item number is the number of non negative integer solutions | polynomial theorem infe
- Thread pool: the most common and error prone component of business code
- [combinatorics] recursive equation (the relationship theorem between the solution of the recursive equation and the characteristic root | the linear property theorem of the solution of the recursive e
- Analysis of variance summary
- What is the difference between 14Cr1MoR container plate and 14Cr1MoR (H)? Chemical composition and performance analysis of 14Cr1MoR
- 深入理解 SQL 中的 Grouping Sets 语句
- Execute script unrecognized \r
- Golang anonymous function use
猜你喜欢
关于学习Qt编程的好书精品推荐
Simulink oscilloscope data is imported into Matlab and drawn
Analysis of variance summary
UCORE overview
CC2530 common registers for watchdog
What material is 12cr1movr? Chemical property analysis of pressure vessel steel plate 12cr1movr
ANOVA example
ucore概述
New features of C 10
Web crawler knowledge day03
随机推荐
Meituan side: why does thread crash not cause JVM crash
Alibaba P8 painstakingly sorted it out. Summary of APP UI automated testing ideas. Check it out
定义一个结构体Fraction,表示分数,用于表示 2/3, 5/6这样的分数
Top k questions of interview
[combinatorics] recursive equation (outline of recursive equation content | definition of recursive equation | example description of recursive equation | Fibonacci Series)
Redis:关于列表List类型数据的操作命令
Overview of satellite navigation system
Kotlin learning quick start (7) -- wonderful use of expansion
Visual studio "usually, each socket address (Protocol / network address / port) can only be used once“
MySQL single table field duplicate data takes the latest SQL statement
[try to hack] active detection and concealment technology
數據分析必備的能力
Acwing game 58
[Jianzhi offer] 57 - ii Continuous positive sequence with sum s
C语言字符串练习
Execute script unrecognized \r
[mathematical logic] equivalent calculus and reasoning calculus of propositional logic (propositional logic | equivalent calculus | principal conjunctive (disjunctive) paradigm | reasoning calculus)**
線程池:業務代碼最常用也最容易犯錯的組件
(补)双指针专题
"The NTP socket is in use, exiting" appears when ntpdate synchronizes the time