当前位置:网站首页>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);
}
};
边栏推荐
- Haut OJ 1401: praise energy
- Daily question - longest substring without repeated characters
- Introduction to convolutional neural network
- Acwing 4300. Two operations
- Codeforces Round #715 (Div. 2) D. Binary Literature
- The connection and solution between the shortest Hamilton path and the traveling salesman problem
- Brief introduction to tcp/ip protocol stack
- One question per day 1447 Simplest fraction
- Simple knapsack, queue and stack with deque
- Codeforces Round #732 (Div. 2) D. AquaMoon and Chess
猜你喜欢
Introduction et expérience de wazuh open source host Security Solution
YOLOv5-Shufflenetv2
Sword finger offer 09 Implementing queues with two stacks
【Jailhouse 文章】Jailhouse Hypervisor
SAP method of modifying system table data
全国中职网络安全B模块之国赛题远程代码执行渗透测试 //PHPstudy的后门漏洞分析
Wazuh开源主机安全解决方案的简介与使用体验
CF1634E Fair Share
How to adjust bugs in general projects ----- take you through the whole process by hand
剑指 Offer 06.从头到尾打印链表
随机推荐
Simply sort out the types of sockets
PC寄存器
Codeforces round 712 (Div. 2) d. 3-coloring (construction)
【Jailhouse 文章】Jailhouse Hypervisor
Animation scoring data analysis and visualization and it industry recruitment data analysis and visualization
Drawing dynamic 3D circle with pure C language
Personal developed penetration testing tool Satania v1.2 update
2022年贵州省职业院校技能大赛中职组网络安全赛项规程
CF1634 F. Fibonacci Additions
One question per day 1765 The highest point in the map
Introduction et expérience de wazuh open source host Security Solution
剑指 Offer 06.从头到尾打印链表
Simple knapsack, queue and stack with deque
EOJ 2021.10 E. XOR tree
1.13 - RISC/CISC
High precision subtraction
Implement a fixed capacity stack
游戏商城毕业设计
Binary search template
[jailhouse article] jailhouse hypervisor