当前位置:网站首页>[556. Next larger element III]
[556. Next larger element III]
2022-07-03 13:41:00 【[email protected]】
source : Power button (LeetCode)
describe :
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
Tips :
1 <= n <= 231 - 1
Method 1 : Next spread
hold n Convert to string ( A character array ), So this problem is actually solving the character array Next spread , Return when there is no next spread −1.
Code :
class Solution {
public:
int nextGreaterElement(int n) {
auto nums = to_string(n);
int i = (int) nums.length() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i < 0) {
return -1;
}
int j = nums.size() - 1;
while (j >= 0 && nums[i] >= nums[j]) {
j--;
}
swap(nums[i], nums[j]);
reverse(nums.begin() + i + 1, nums.end());
long ans = stol(nums);
return ans > INT_MAX ? -1 : ans;
}
};
Execution time :0 ms, In all C++ Defeated in submission 100.00% Users of
Memory consumption :5.8 MB, In all C++ Defeated in submission 57.91% Users of
Complexity analysis
Time complexity : O(logn).
Spatial complexity :O O(logn).
Method 2 : mathematics
Do not convert to character array , How to use O(1) Space complexity to solve this problem ?
If not required 64 Bit integer ?
Similar method I , We from n Start , Constantly compare the size of the lowest digit and the second lowest digit , If the next lowest digit is not lower than the lowest digit , Then remove the lowest digit , Continue to cycle . At the end of the cycle n It corresponds to the subscript of method one i, namely nums Before i + 1 Characters .
For method one, the subscript j The same is true for the calculation of .
Code :
class Solution {
public:
int nextGreaterElement(int n) {
int x = n, cnt = 1;
for (; x >= 10 && x / 10 % 10 >= x % 10; x /= 10) {
++cnt;
}
x /= 10;
if (x == 0) {
return -1;
}
int targetDigit = x % 10;
int x2 = n, cnt2 = 0;
for (; x2 % 10 <= targetDigit; x2 /= 10) {
++cnt2;
}
x += x2 % 10 - targetDigit; // hold x2 % 10 Switch to targetDigit On
for (int i = 0; i < cnt; ++i, n /= 10) {
// reverse n Last cnt Spell the numbers to x after
int d = i != cnt2 ? n % 10 : targetDigit;
if (x > INT_MAX / 10 || x == INT_MAX / 10 && d > 7) {
return -1;
}
x = x * 10 + d;
}
return x;
}
};
Execution time :0 ms, In all C++ Defeated in submission 100.00% Users of
Memory consumption :5.7 MB, In all C++ Defeated in submission 94.76% Users of
Complexity analysis
Time complexity : O(logn).
Spatial complexity : O(1). We just need a constant space to hold a few variables .
author:LeetCode-Solution
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/184/202207031310265002.html
边栏推荐
- Bidirectional linked list (we only need to pay attention to insert and delete functions)
- Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
- [quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
- 服务器硬盘冷迁移后网卡无法启动问题
- Spark实战1:单节点本地模式搭建Spark运行环境
- Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
- Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
- Typeerror resolved: argument 'parser' has incorrect type (expected lxml.etree.\u baseparser, got type)
- 【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
- 刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?
猜你喜欢

Mycms we media mall v3.4.1 release, user manual update
![[sort] bucket sort](/img/52/95514b5a70cea75821883e016d8adf.jpg)
[sort] bucket sort

Flutter dynamic | fair 2.5.0 new version features
![[redis] cache warm-up, cache avalanche and cache breakdown](/img/df/81f38087704de36946b470f68e8004.jpg)
[redis] cache warm-up, cache avalanche and cache breakdown

双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆

Error running 'application' in idea running: the solution of command line is too long

PowerPoint tutorial, how to save a presentation as a video in PowerPoint?

MySQL installation, uninstallation, initial password setting and general commands of Linux
![[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay](/img/18/b06e2e5a2f76dc2da1c2374b8424b3.png)
[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay
[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈..."/>开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
随机推荐
SQL Injection (POST/Search)
顺序表(C语言实现)
8皇后问题
Task6: using transformer for emotion analysis
Anan's doubts
用户和组命令练习
JS 将伪数组转换成数组
Error running 'application' in idea running: the solution of command line is too long
Multi table query of MySQL - multi table relationship and related exercises
User and group command exercises
Smbms project
Logseq 评测:优点、缺点、评价、学习教程
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
Which securities company has the lowest Commission for opening an account online? I want to open an account. Is it safe for the online account manager to open an account
服务器硬盘冷迁移后网卡无法启动问题
php 迷宫游戏
【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
Disruptor -- a high concurrency and high performance queue framework for processing tens of millions of levels
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion