当前位置:网站首页>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);
}
};
边栏推荐
- Sword finger offer 05 Replace spaces
- Zheng Qing 21 ACM is fun. (3) part of the problem solution and summary
- Binary search template
- YOLOv5-Shufflenetv2
- Mysql database (I)
- [practical skills] technical management of managers with non-technical background
- Wazuh开源主机安全解决方案的简介与使用体验
- 每日一题-搜索二维矩阵ps二维数组的查找
- Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
- Light a light with stm32
猜你喜欢
随机推荐
Kubedm series-00-overview
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
1.13 - RISC/CISC
Summary of Haut OJ 2021 freshman week
【实战技能】如何做好技术培训?
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
Transform optimization problems into decision-making problems
Bit mask of bit operation
Haut OJ 2021 freshmen week II reflection summary
2022年貴州省職業院校技能大賽中職組網絡安全賽項規程
CF1637E Best Pair
Palindrome (csp-s-2021-palin) solution
SAP method of modifying system table data
用STM32点个灯
Haut OJ 1401: praise energy
Daily question 1688 Number of matches in the competition
Mysql database (I)
Solution to game 10 of the personal field
数仓项目的集群脚本
CF1634E Fair Share


![[article de jailhouse] jailhouse hypervisor](/img/f4/4809b236067d3007fa5835bbfe5f48.png)






