当前位置:网站首页>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
边栏推荐
- pragma-pack语法与使用
- Shutter: about inheritedwidget
- shardingSphere分库分表<3>
- vulnhub之GeminiInc
- Xiaopeng P7 hit the guardrail and the airbag did not pop up. The official responded that the impact strength did not meet the ejection requirements
- OpenGL index cache object EBO and lineweight mode
- vulnhub之Ripper
- Laravel time zone timezone
- rxjs Observable filter Operator 的实现原理介绍
- laravel 时区问题timezone
猜你喜欢

Pki/ca and digital certificate

(construction notes) ADT and OOP

Solve msvcp120d DLL and msvcr120d DLL missing

《剑指offer 04》二维数组查找

Is BigDecimal safe to calculate the amount? Look at these five pits~~

Laravel time zone timezone

4000 word super detailed pointer

Solution to the second weekly test of ACM intensive training of Hunan Institute of technology in 2022

XML (DTD, XML parsing, XML modeling)

《剑指offer 03》数组中重复的数字
随机推荐
MCDF Experiment 1
PHP export word method (one MHT)
Redis notes 01: Introduction
DNS multi-point deployment IP anycast+bgp actual combat analysis
4000字超详解指针
[learning notes] DP status and transfer
Qt OpenGL 纹理贴图
Go language to realize static server
rxjs Observable filter Operator 的实现原理介绍
CGroup introduction
Quantitative calculation research
vulnhub之tomato(西红柿)
SystemVerilog -- OOP -- copy of object
Flutter: self study system
《剑指offer 03》数组中重复的数字
4000 word super detailed pointer
Shardingsphere sub database and sub table < 3 >
vulnhub之presidential
DNS多点部署IP Anycast+BGP实战分析
QT OpenGL rotate, pan, zoom