当前位置:网站首页>JS解力扣每日一题(十二)——556. 下一个更大元素 III(2022-7-3)
JS解力扣每日一题(十二)——556. 下一个更大元素 III(2022-7-3)
2022-07-05 18:40:00 【rjlmylove_zyw】
题目
给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n 中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1 。
注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1 。
示例1
输入:n = 12
输出:21
我的答案
var nextGreaterElement = function(n) {
const nums = String(n).split('').map((num) => + num)
let i = nums.length - 1
let j = i
const stack = []
for (; i >= 0; i --) {
if (stack.length && nums[i] < nums[stack[stack.length - 1]]) {
while (stack.length && nums[i] < nums[stack[stack.length - 1]]) {
j = stack.pop()
}
break
}
stack.push(i)
}
if (i < 0) {
return -1
}
[nums[i], nums[j]] = [nums[j], nums[i]]
const ans = +(nums.slice(0, i + 1).join('') + nums.slice(i + 1).sort((a, b) => a - b).join(''))
return ans > 2147483647 ? -1 : ans
};
边栏推荐
- 小程序 修改样式 ( placeholder、checkbox的样式)
- 华律网牵手观测云,上线系统全链路可观测平台
- R language uses lubridate package to process date and time data
- ICML2022 | 长尾识别中分布外检测的部分和非对称对比学习
- 面试官:Redis 过期删除策略和内存淘汰策略有什么区别?
- RPC protocol details
- 一朵云开启智慧交通新未来
- Interviewer: what is the difference between redis expiration deletion strategy and memory obsolescence strategy?
- 如何写出好代码 - 防御式编程
- 华为让出的高端市场,小米12S靠徕卡能抢到吗?
猜你喜欢
[today in history] July 5: the mother of Google was born; Two Turing Award pioneers born on the same day
Shang Silicon Valley Shang preferred project tutorial release
Oracle 中文排序 Oracle 中文字段排序
如何写出好代码 - 防御式编程
Applet modification style (placeholder, checkbox style)
Oracle Chinese sorting Oracle Chinese field sorting
Isprs2022/ cloud detection: cloud detection with boundary nets
Summary of six points of MySQL optimization
Use QT to traverse JSON documents and search sub objects
Redhat7.4 configure Yum software warehouse (rhel7.4)
随机推荐
cf:B. Almost Ternary Matrix【对称 + 找规律 + 构造 + 我是构造垃圾】
The monthly list of Tencent cloud developer community videos was released in May 2022
2022年5月腾讯云开发者社区视频月度榜单公布
Quickly generate IPA package
Word finds red text word finds color font word finds highlighted formatted text
Mysql database indexing tutorial (super detailed)
RPC protocol details
EasyCVR电子地图中设备播放器loading样式的居中对齐优化
lombok @Builder注解
自动化测试的好处
2022 latest Android interview written examination, an Android programmer's interview experience
XML基础知识概念
Linear table - abstract data type
A cloud opens a new future of smart transportation
All you want to know about clothing ERP is here
RedHat7.4配置yum软件仓库(RHEL7.4)
尚硅谷尚优选项目教程发布
案例分享|金融业数据运营运维一体化建设
Tupu software digital twin | visual management system based on BIM Technology
图扑软件数字孪生 | 基于 BIM 技术的可视化管理系统