当前位置:网站首页>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);
}
};
边栏推荐
- CCPC Weihai 2021m eight hundred and ten thousand nine hundred and seventy-five
- One question per day 1765 The highest point in the map
- 2022 pole technology communication arm virtual hardware accelerates the development of Internet of things software
- Implement an iterative stack
- Daily question 1688 Number of matches in the competition
- 2017 USP Try-outs C. Coprimes
- Time complexity and space complexity
- AtCoder Grand Contest 013 E - Placing Squares
- Detailed explanation of expression (csp-j 2021 expr) topic
- Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
猜你喜欢

Wazuh开源主机安全解决方案的简介与使用体验

In this indifferent world, light crying

EOJ 2021.10 E. XOR tree

sync. Interpretation of mutex source code

剑指 Offer 05. 替换空格
![[jailhouse article] jailhouse hypervisor](/img/f4/4809b236067d3007fa5835bbfe5f48.png)
[jailhouse article] jailhouse hypervisor

用STM32点个灯

Fried chicken nuggets and fifa22

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

Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
随机推荐
After setting up the database and website When you open the app for testing, it shows that the server is being maintained
Educational codeforces round 109 (rated for Div. 2) C. robot collisions D. armchairs
【Jailhouse 文章】Performance measurements for hypervisors on embedded ARM processors
Brief introduction to tcp/ip protocol stack
shared_ Repeated release heap object of PTR hidden danger
Time of process
Kubedm series-00-overview
智慧工地“水电能耗在线监测系统”
[jailhouse article] performance measurements for hypervisors on embedded ARM processors
kubeadm系列-02-kubelet的配置和启动
剑指 Offer 53 - I. 在排序数组中查找数字 I
Convolution neural network -- convolution layer
【Jailhouse 文章】Jailhouse Hypervisor
剑指 Offer 35.复杂链表的复制
Scope of inline symbol
中职网络安全技能竞赛——广西区赛中间件渗透测试教程文章
CCPC Weihai 2021m eight hundred and ten thousand nine hundred and seventy-five
2020ccpc Qinhuangdao J - Kingdom's power
Using HashMap to realize simple cache
Sword finger offer 05 Replace spaces