当前位置:网站首页>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 Export word method (One MHT)
- [learning notes] DP status and transfer
- C language improvement article (wchar_t) character type
- DEJA_VU3D - Cesium功能集 之 053-地下模式效果
- [combinatorics] permutation and combination (summary of permutation and combination content | selection problem | set permutation | set combination)
- Dart: About zone
- Shutter: add gradient stroke to font
- "Jianzhi offer 04" two-dimensional array search
- (构造笔记)从类、API、框架三个层面学习如何设计可复用软件实体的具体技术
- 错排问题 (抽奖,发邮件)
猜你喜欢
Vulnhub narak
Shutter: add gradient stroke to font
牛牛的组队竞赛
ES6新特性
【mysql专项】读锁和写锁
MCDF Experiment 1
Quantitative calculation research
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
QT OpenGL rotate, pan, zoom
Vulnhub's Nagini
随机推荐
DNS多点部署IP Anycast+BGP实战分析
Dart: about grpc (I)
网络通讯之Socket-Tcp(一)
OpenGL index cache object EBO and lineweight mode
vulnhub之momentum
Unity3d learning notes 5 - create sub mesh
安装electron失败的解决办法
PHP export word method (one MHT)
Shutter: overview of shutter architecture (excerpt)
rxjs Observable filter Operator 的实现原理介绍
[learning notes] DP status and transfer
Dart: view the dill compiled code file
Use of QT OpenGL camera
Niuniu's team competition
Flutter Widget : KeyedSubtree
Quantitative calculation research
Vulnhub geminiinc V2
vulnhub之pyexp
抓包整理外篇fiddler———— 会话栏与过滤器[二]
win10 上PHP artisan storage:link 出现 symlink (): Protocol error的解决办法