forked from lzl124631x/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths2.cpp
More file actions
21 lines (21 loc) · 692 Bytes
/
s2.cpp
File metadata and controls
21 lines (21 loc) · 692 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// OJ: https://leetcode.com/problems/previous-permutation-with-one-swap/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
vector<int> prevPermOpt1(vector<int>& A) {
stack<pair<int, int>> s;
int first = -1, second = -1;
for (int i = 0; i < A.size(); ++i) {
while (s.size() && A[i] >= s.top().second) s.pop();
if (s.size() && (s.top().first >= second || (s.top().first == first && A[i] != A[second]))) {
first = s.top().first;
second = i;
}
s.emplace(i, A[i]);
}
if (first > -1) swap(A[first], A[second]);
return A;
}
};