We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 15fa32f commit 46f94b5Copy full SHA for 46f94b5
Math/556.md
@@ -0,0 +1,40 @@
1
+## 556 Next Greater Element III
2
+
3
+#### Description
4
5
+[link](https://leetcode.com/problems/next-greater-element-iii/)
6
7
+---
8
9
+#### Solution
10
11
+- 下一个排列问题,先从后往前找到第一个不是递减的数字,和后面第一个大于它的数字交换,如果没有变化或者过大,返回-1
12
13
14
15
+#### Code
16
17
+<!-- O(n) -->
18
19
+```python
20
+class Solution:
21
+ def nextGreaterElement(self, n: int) -> int:
22
+ digits = list(str(n))
23
+ length = len(digits)
24
25
+ i, j = length-2, length-1
26
+ while i >= 0 and digits[i+1] <= digits[i]:
27
+ i -= 1
28
29
+ if i == -1: return -1
30
31
+ while digits[j] <= digits[i]:
32
+ j -= 1
33
34
+ digits[i], digits[j] = digits[j], digits[i]
35
36
+ res = int(''.join(digits[:i+1] + digits[i+1:][::-1]))
37
+ if res >= 2**31 or res == n:
38
+ return -1
39
+ return res
40
+```
0 commit comments