当前位置:网站首页>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);
}
};
边栏推荐
- 1.13 - RISC/CISC
- Detailed explanation of expression (csp-j 2021 expr) topic
- Sword finger offer 53 - ii Missing numbers from 0 to n-1
- [jailhouse article] look mum, no VM exits
- Sword finger offer 35 Replication of complex linked list
- Smart construction site "hydropower energy consumption online monitoring system"
- One question per day 1765 The highest point in the map
- Acwing 4301. Truncated sequence
- Pointnet++ learning
- Educational Codeforces Round 116 (Rated for Div. 2) E. Arena
猜你喜欢

SAP method of modifying system table data

Introduction et expérience de wazuh open source host Security Solution

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

Some common problems in the assessment of network engineers: WLAN, BGP, switch

Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module

CF1637E Best Pair

1.14 - 流水线

How to adjust bugs in general projects ----- take you through the whole process by hand

【实战技能】非技术背景经理的技术管理

用STM32点个灯
随机推荐
Individual game 12
QT判断界面当前点击的按钮和当前鼠标坐标
Analysis of backdoor vulnerability in remote code execution penetration test / / phpstudy of national game title of national secondary vocational network security B module
Implement a fixed capacity stack
剑指 Offer 09. 用两个栈实现队列
Drawing dynamic 3D circle with pure C language
Some common problems in the assessment of network engineers: WLAN, BGP, switch
Graduation project of game mall
Hang wait lock vs spin lock (where both are used)
Haut OJ 1401: praise energy
[practical skills] technical management of managers with non-technical background
Sword finger offer 58 - ii Rotate string left
Daily question - Search two-dimensional matrix PS two-dimensional array search
Sword finger offer 53 - I. find the number I in the sorted array
API related to TCP connection
R语言【数据集的导入导出】
Wazuh开源主机安全解决方案的简介与使用体验
Reader writer model
【实战技能】非技术背景经理的技术管理
26、 File system API (device sharing between applications; directory and file API)