当前位置:网站首页>LeetCode 0556.下一个更大元素 III - 4步讲完
LeetCode 0556.下一个更大元素 III - 4步讲完
2022-07-03 11:31:00 【Tisfy】
【LetMeFly】4步讲完:556.下一个更大元素 III
力扣题目链接:https://leetcode.cn/problems/next-greater-element-iii/
给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1 。
注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1 。
示例 1:
输入:n = 12 输出:21
示例 2:
输入:n = 21 输出:-1
提示:
1 <= n <= 231 - 1
方法一:模拟
其实就是求数字对应字符串的下一个全排列,方法也很简单(4步):
从后往前看,找到第一个“后面有大于它的数”的数(记为s[i] = x)
在s[i ~ 最后]中找到最小的大于x的数(记为s[j] = y)
交换s[i]和s[j]
在s[i+1 ~ 最后]范围内从小到大排序
然后返回字符串对应的数字即可
- 时间复杂度 O ( N 2 ) O(N^2) O(N2),其中 N N N是数字的位数( N ≤ 10 N\leq 10 N≤10)
- 空间复杂度 O ( N log N ) O(N\log N) O(NlogN),空间复杂度主要是排序所致
AC代码
C++
class Solution {
public:
int nextGreaterElement(int n) {
string s = to_string(n);
bool changed = false;
for (int i = s.size() - 2; i >= 0; i--) {
char m = 58; // '9' = 57
int locm = i;
for (int j = i + 1; j < s.size(); j++) {
if (s[j] > s[i] && s[j] < m) {
m = s[j];
locm = j;
}
}
if (locm != i) {
changed = true;
swap(s[i], s[locm]);
sort(s.begin() + i + 1, s.end());
break;
}
}
if (!changed)
return -1;
ll ans = atoll(s.c_str());
if (ans > INT_MAX)
return -1;
return ans;
}
};
小小记录一下嘿嘿

同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/125582351
边栏推荐
- PHP get the file list and folder list under the folder
- Unity3d learning notes 5 - create sub mesh
- 网络通讯之Socket-Tcp(一)
- Ripper of vulnhub
- Flutter Widget : KeyedSubtree
- [combinatorics] permutation and combination (example of permutation and combination)
- ES6新特性
- Is BigDecimal safe to calculate the amount? Look at these five pits~~
- OpenGL 着色器使用
- Test classification in openstack
猜你喜欢
随机推荐
DEJA_ Vu3d - cesium feature set 053 underground mode effect
Dart: About zone
DNS multi-point deployment IP anycast+bgp actual combat analysis
vulnhub之tomato(西红柿)
Oracle advanced (I) realize DMP by expdp impdp command
libvirt 中体验容器
ArcGIS application (XXI) ArcMap method of deleting layer specified features
Simple factory and factory method mode
ES6新特性
XML (DTD, XML parsing, XML modeling)
vulnhub之raven2
PHP export word method (one MHT)
Symlink(): solution to protocol error in PHP artisan storage:link on win10
(数据库提权——Redis)Redis未授权访问漏洞总结
Cacti monitors redis implementation process
SLF4J 日志门面
Duplicate numbers in the array of sword finger offer 03
Flutter Widget : Flow
vulnhub之cereal
How to convert a numeric string to an integer









