当前位置:网站首页>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);
}
};
边栏推荐
- R language [import and export of dataset]
- 全排列的代码 (递归写法)
- 浅谈JVM(面试常考)
- Daily question 1688 Number of matches in the competition
- Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
- The sum of the unique elements of the daily question
- CF1634E Fair Share
- 全国中职网络安全B模块之国赛题远程代码执行渗透测试 //PHPstudy的后门漏洞分析
- Solution to the palindrome string (Luogu p5041 haoi2009)
- Time of process
猜你喜欢
[practical skills] how to do a good job in technical training?
Sword finger offer 05 Replace spaces
How to adjust bugs in general projects ----- take you through the whole process by hand
CF1637E Best Pair
Implement an iterative stack
1.13 - RISC/CISC
Chapter 6 data flow modeling - after class exercises
Palindrome (csp-s-2021-palin) solution
Personal developed penetration testing tool Satania v1.2 update
LeetCode 0107.二叉树的层序遍历II - 另一种方法
随机推荐
Educational Codeforces Round 107 (Rated for Div. 2) E. Colorings and Dominoes
Sword finger offer 09 Implementing queues with two stacks
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
智慧工地“水电能耗在线监测系统”
The number of enclaves
SAP method of modifying system table data
【Jailhouse 文章】Performance measurements for hypervisors on embedded ARM processors
EOJ 2021.10 E. XOR tree
Fried chicken nuggets and fifa22
[cloud native] record of feign custom configuration of microservices
Introduction and experience of wazuh open source host security solution
Little known skills of Task Manager
Talking about JVM (frequent interview)
7. Processing the input of multidimensional features
2022年贵州省职业院校技能大赛中职组网络安全赛项规程
Wazuh开源主机安全解决方案的简介与使用体验
Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
网络工程师考核的一些常见的问题:WLAN、BGP、交换机
Kubedm series-00-overview
ALU逻辑运算单元