当前位置:网站首页>leetcode-556:下一个更大元素 III
leetcode-556:下一个更大元素 III
2022-07-05 05:46:00 【菊头蝙蝠】
题目
给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n 中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1 。
注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1 。
示例 1:
输入:n = 12
输出:21
示例 2:
输入:n = 21
输出:-1
解题
和leetcode-31:下一个排列相同的思路,只是要在它的基础上,多了溢出判断
方法一:
class Solution {
public:
//溢出判断
bool isValidInt(string& s){
string maxS=to_string(INT_MAX);
if(s.size()<maxS.size()) return true;
for(int i=0;i<s.size();i++){
if(s[i]>maxS[i]) return false;
else if(s[i]==maxS[i]) continue;
else if(s[i]<maxS[i]) return true;
}
return true;
}
int nextGreaterElement(int n) {
string s=to_string(n);
int len=s.size();
int i=len-2,j=len-1;
while(i>=0&&s[i]>=s[j]){
i--;
j--;
}
if(i<0) return -1;
int k=len-1;
while(s[i]>=s[k]){
k--;
}
swap(s[i],s[k]);
sort(s.begin()+i+1,s.end());
if(!isValidInt(s)) return -1;
else return stoi(s);
}
};
边栏推荐
- PC register
- [cloud native] record of feign custom configuration of microservices
- 过拟合与正则化
- 常见的最优化方法
- [jailhouse article] jailhouse hypervisor
- The sum of the unique elements of the daily question
- Codeforces round 712 (Div. 2) d. 3-coloring (construction)
- Sword finger offer 35 Replication of complex linked list
- 从Dijkstra的图灵奖演讲论科技创业者特点
- Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
猜你喜欢
![[practical skills] how to do a good job in technical training?](/img/a3/7a1564cd9eb564abfd716fef08a9e7.jpg)
[practical skills] how to do a good job in technical training?

中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章

Time of process

Reader writer model

LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树

剑指 Offer 06.从头到尾打印链表

【Jailhouse 文章】Jailhouse Hypervisor

Implement an iterative stack

How to adjust bugs in general projects ----- take you through the whole process by hand

API related to TCP connection
随机推荐
Over fitting and regularization
Full Permutation Code (recursive writing)
Mysql database (I)
Sword finger offer 04 Search in two-dimensional array
LeetCode 0108.将有序数组转换为二叉搜索树 - 数组中值为根,中值左右分别为左右子树
剑指 Offer 06.从头到尾打印链表
6. Logistic model
【实战技能】如何做好技术培训?
Common optimization methods
Corridor and bridge distribution (csp-s-2021-t1) popular problem solution
1996. number of weak characters in the game
Control Unit 控制部件
Sword finger offer 58 - ii Rotate string left
剑指 Offer 58 - II. 左旋转字符串
Simple knapsack, queue and stack with deque
[jailhouse article] look mum, no VM exits
Implement an iterative stack
Dynamic planning solution ideas and summary (30000 words)
Collection: programming related websites and books
kubeadm系列-02-kubelet的配置和启动