forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2289.Steps-to-Make-Array-Non-decreasing_v1.cpp
48 lines (43 loc) · 1.24 KB
/
2289.Steps-to-Make-Array-Non-decreasing_v1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
int totalSteps(vector<int>& nums)
{
int n = nums.size();
list<int> List;
unordered_map<int,list<int>::iterator>idx2iter;
for (int i=0; i<n; i++)
{
List.push_back(i);
idx2iter[i] = prev(List.end());
}
queue<int>q;
for (int i=n-1; i>=1; i--)
if (nums[i-1]>nums[i])
q.push(i);
int step = 0;
while (!q.empty())
{
int len = q.size();
vector<int>temp;
while (len--)
{
int i = q.front();
q.pop();
auto iter = idx2iter[i];
if (next(iter)!=List.end() && (temp.empty() || *next(iter)!=temp.back()))
{
temp.push_back(*next(iter));
}
List.erase(iter);
}
for (int idx: temp)
{
auto iter = idx2iter[idx];
if (iter!=List.begin() && nums[*prev(iter)] > nums[idx])
q.push(idx);
}
step++;
}
return step;
}
};