当前位置:网站首页>Leetcode-556: the next larger element III
Leetcode-556: the next larger element III
2022-07-05 06:09:00 【Chrysanthemum headed bat】
leetcode-556: Next bigger element III
subject
Give you a positive integer n , Please find the smallest integer that meets the conditions , It consists of rearranging n Each number present in the consists of , And its value is greater than n . If there is no such positive integer , Then return to -1 .
Be careful , The returned integer should be a 32 An integer , If there is an answer that satisfies the meaning of the question , But it's not 32 An integer , Also return to -1 .
Example 1:
Input :n = 12
Output :21
Example 2:
Input :n = 21
Output :-1
Problem solving
and leetcode-31: Next spread Same idea , Just based on it , Excessive overflow judgment
Method 1 :
class Solution {
public:
// Overflow judgment
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);
}
};
边栏推荐
猜你喜欢

Dichotomy, discretization, etc

Spark中groupByKey() 和 reduceByKey() 和combineByKey()

AtCoder Grand Contest 013 E - Placing Squares

可变电阻器概述——结构、工作和不同应用

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

Data visualization chart summary (I)

Implement a fixed capacity stack

Brief introduction to tcp/ip protocol stack

In this indifferent world, light crying

7. Processing the input of multidimensional features
随机推荐
Fried chicken nuggets and fifa22
leetcode-556:下一个更大元素 III
Convolution neural network -- convolution layer
QQ computer version cancels escape character input expression
CF1637E Best Pair
The difference between CPU core and logical processor
7. Processing the input of multidimensional features
MIT-6874-Deep Learning in the Life Sciences Week 7
【Jailhouse 文章】Jailhouse Hypervisor
Codeforces Round #716 (Div. 2) D. Cut and Stick
1996. number of weak characters in the game
剑指 Offer II 058:日程表
Wazuh開源主機安全解决方案的簡介與使用體驗
打印机脱机时一种容易被忽略的原因
Full Permutation Code (recursive writing)
“磐云杯”中职网络安全技能大赛A模块新题
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库
Error ora-28547 or ora-03135 when Navicat connects to Oracle Database
2022 极术通讯-Arm 虚拟硬件加速物联网软件开发
【Rust 笔记】16-输入与输出(下)