当前位置:网站首页>556. 下一个更大元素 III : 简单构造模拟题
556. 下一个更大元素 III : 简单构造模拟题
2022-07-03 14:31:00 【宫水三叶的刷题日记】
题目描述
这是 LeetCode 上的 556. 下一个更大元素 III ,难度为 中等。
Tag : 「模拟」、「双指针」
给你一个正整数 ,请你找出符合条件的最小整数,其由重新排列 中存在的每位数字组成,并且其值大于 。如果不存在这样的正整数,则返回 。
注意 ,返回的整数应当是一个 位整数 ,如果存在满足题意的答案,但不是 位整数 ,同样返回 。
示例 1:
输入:n = 12
输出:21
示例 2:
输入:n = 21
输出:-1
提示:
模拟
根据题意,只有给定数字 本身从高位到低位是「非严格降序」时,我们无法找到一个合法值。
首先,我们可以先对 诸位取出,存成 nums 数组(数组的首位元素为原数 的最低位)。
然后尝试找到第一个能够交换的位置 idx(若无法找到,说明不存在合法值,返回 ),即从 (原始 的最低位)开始找,找到第一个「降序」的位置 idx,然后从 范围内找一个比 要大的最小数与其进行互换,也是从 开始找,找到第一个满足比 大的数。
当互换完成后,此时比 要大这一目标已由第 idx 位所保证(后续的排序应该按照从小到大放置),同时互换结束后的 仍然满足「非严格升序」特性,因此我们可以对其运用「双指针」进行翻转。
代码:
class Solution {
public int nextGreaterElement(int x) {
List<Integer> nums = new ArrayList<>();
while (x != 0) {
nums.add(x % 10);
x /= 10;
}
int n = nums.size(), idx = -1;
for (int i = 0; i < n - 1 && idx == -1; i++) {
if (nums.get(i + 1) < nums.get(i)) idx = i + 1;
}
if (idx == -1) return -1;
for (int i = 0; i < idx; i++) {
if (nums.get(i) > nums.get(idx)) {
swap(nums, i, idx);
break;
}
}
for (int l = 0, r = idx - 1; l < r; l++, r--) swap(nums, l, r);
long ans = 0;
for (int i = n - 1; i >= 0; i--) ans = ans * 10 + nums.get(i);
return ans > Integer.MAX_VALUE ? -1 : (int)ans;
}
void swap(List<Integer> nums, int a, int b) {
int c = nums.get(a);
nums.set(a, nums.get(b));
nums.set(b, c);
}
}
时间复杂度: 空间复杂度:
最后
这是我们「刷穿 LeetCode」系列文章的第 No.556 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
边栏推荐
猜你喜欢

Doris学习笔记之数据表的创建

7-15 calculation of PI

puzzle(016.3)千丝万缕

tonybot 人形机器人 定距移动 代码编写玩法

US stock listing of polar: how can the delivery of 55000 units support the valuation of more than 20billion US dollars
![[clean up the extraordinary image of Disk C]](/img/0d/331115bc5d82d6337ae975a08494b2.jpg)
[clean up the extraordinary image of Disk C]

ConstraintLayout 的使用

7-18 finding the single root of polynomial by dichotomy

X86 assembly language - Notes from real mode to protected mode

愉悦资本新双币基金近40亿元完成首次关账
随机推荐
剑指 Offer 28. 对称的二叉树
7-2 and then what time (15 minutes)
NPM install is stuck with various strange errors of node NPY
2021年区域赛ICPC沈阳站J-Luggage Lock(代码简洁)
7-28 monkeys choose King (Joseph problem)
Leetcode(4)——寻找两个正序数组的中位数
US stock listing of polar: how can the delivery of 55000 units support the valuation of more than 20billion US dollars
7-14 sum integer segments (C language)
编程语言:类型系统的本质
7-9 find a small ball with a balance
7-8 overspeed judgment
puzzle(016.4)多米诺效应
【北大青鸟昌平校区】互联网行业中,哪些岗位越老越吃香?
Concat and concat_ Ws() differences and groups_ Use of concat() and repeat() functions
修改数据库中的记录为什么报这个错
Leetcode(4)——尋找兩個正序數組的中比特數
pyQt界面制作(登录+跳转页面)
Sword finger offer 28 Symmetric binary tree
别再问自己适不适合做软件测试了
Mysql多表查询 #子查询