当前位置:网站首页>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
边栏推荐
- 4000 word super detailed pointer
- STL Tutorial 9 deep copy and shallow copy of container elements
- vulnhub之GeminiInc v2
- Keepalived中Master和Backup角色选举策略
- Duplicate numbers in the array of sword finger offer 03
- Test classification in openstack
- Shutter widget: centerslice attribute
- Qt OpenGL相机的使用
- 牛牛的组队竞赛
- Php Export word method (One MHT)
猜你喜欢
随机推荐
win10 上PHP artisan storage:link 出现 symlink (): Protocol error的解决办法
Socket TCP for network communication (I)
Ripper of vulnhub
安裝electron失敗的解决辦法
《剑指offer 03》数组中重复的数字
小鹏 P7 撞护栏安全气囊未弹出,官方回应称撞击力度未达到弹出要求
Basic knowledge of OpenGL (sort it out according to your own understanding)
Socket TCP for network communication (I)
Experience container in libvirt
Flutter: self study system
previous permutation lintcode51
[learning notes] DP status and transfer
Solution to the second weekly test of ACM intensive training of Hunan Institute of technology in 2022
Qt OpenGL 旋转、平移、缩放
C language improvement article (wchar_t) character type
Flutter: about monitoring on flutter applications
(construction notes) grasp learning experience
OpenGL shader use
Unicode encoding table download
laravel 时区问题timezone









