当前位置:网站首页>leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】
2022-07-03 18:38:00 【白速龙王的回眸】
分析
如果已经最大就返回-1
否则,肯定有一个前面的数比后面的要小的,我们交换它
然后我们要让前面的数尽量靠后即可
交换完之后,我们要对这个数后面的数进行重排(保证最小升序)
还要注意要在32位整数范围内,否则-1
ac code
class Solution:
def nextGreaterElement(self, n: int) -> int:
flag = False
s = str(n)
if len(s) == 1:
return -1
for i in range(1, len(s)):
if s[i] > s[i - 1]:
flag = True
if not flag:
return -1
lst = list(s)
idx = 0
for i in range(len(lst)):
for j in range(i):
if lst[len(s) - 1 - j] > lst[len(s) - 1 - i]:
lst[len(s) - 1 - j], lst[len(s) - 1 - i] = lst[len(s) - 1 - i], lst[len(s) - 1 - j]
flag = False
idx = len(s) - 1 - i
break
if not flag:
break
# idx后面的重排
temp = lst[idx + 1:]
temp.sort()
lst[idx + 1:] = temp[:]
ans = int(''.join(lst))
return ans if ans <= 2 ** 31 - 1 else -1
总结
下一个排列
找到交互变大最小的两个数(头一个尽量靠后,后一个也尽量靠后即可)
然后对头一个后面的进行升序重拍即可
边栏推荐
- CTO and programmer were both sentenced for losing control of the crawler
- Mysql45 lecture learning notes (II)
- Golang string (string) and byte array ([]byte) are converted to each other
- 2022-2028 global petroleum pipe joint industry research and trend analysis report
- 12、 Service management
- Common PostgreSQL commands
- Computer graduation design PHP makeup sales Beauty shopping mall
- G1 garbage collector of garbage collector
- Suffix derivation based on query object fields
- Database creation, addition, deletion, modification and query
猜你喜欢
[combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*
Summary and Reflection on the third week of winter vacation
Sensor debugging process
Redis cache avalanche, penetration, breakdown
2022-2028 global plasmid DNA cdmo industry research and trend analysis report
Sensor 调试流程
What is SQL get connection
Implementation of cqrs architecture mode under Kratos microservice framework
my. INI file not found
Prototype inheritance..
随机推荐
Sepconv (separable revolution) code recurrence
Caddy server agent
Suffix derivation based on query object fields
Niuke monthly race 31 minus integer
After the festival, a large number of people change careers. Is it still time to be 30? Listen to the experience of the past people
Graduation summary
PHP determines which constellation it belongs to today
12、 Service management
Redis cache avalanche, penetration, breakdown
Real time split network (continuous update)
Shell script return value with which output
189. Rotation array
English语法_名词 - 分类
Closure and closure function
2022-2028 global scar care product industry research and trend analysis report
Okaleido, a multimedia NFT aggregation platform, is about to go online, and a new NFT era may come
Naoqi robot summary 27
Setinterval CPU intensive- Is setInterval CPU intensive?
Boost. Asio Library
What London Silver Trading software supports multiple languages