mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0738.单调递增的数字.md
java原先版本中创建了String数组,多次使用Integer.parseInt了方法,这导致不管是耗时还是空间占用都非常高,用时12ms,下面提供一个版本在char数组上原地修改,用时1ms的版本
This commit is contained in:
@ -127,6 +127,7 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```java
|
||||||
|
版本1
|
||||||
class Solution {
|
class Solution {
|
||||||
public int monotoneIncreasingDigits(int N) {
|
public int monotoneIncreasingDigits(int N) {
|
||||||
String[] strings = (N + "").split("");
|
String[] strings = (N + "").split("");
|
||||||
@ -144,6 +145,31 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
java版本1中创建了String数组,多次使用Integer.parseInt了方法,这导致不管是耗时还是空间占用都非常高,用时12ms,下面提供一个版本在char数组上原地修改,用时1ms的版本
|
||||||
|
```java
|
||||||
|
版本2
|
||||||
|
class Solution {
|
||||||
|
public int monotoneIncreasingDigits(int n) {
|
||||||
|
if (n==0)return 0;
|
||||||
|
char[] chars= Integer.toString(n).toCharArray();
|
||||||
|
int start=Integer.MAX_VALUE;//start初始值设为最大值,这是为了防止当数字本身是单调递增时,没有一位数字需要改成9的情况
|
||||||
|
for (int i=chars.length-1;i>0;i--){
|
||||||
|
if (chars[i]<chars[i-1]){
|
||||||
|
chars[i-1]--;
|
||||||
|
start=i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
StringBuilder res=new StringBuilder();
|
||||||
|
for (int i=0;i<chars.length;i++){
|
||||||
|
if (chars[i]=='0'&&i==0)continue;//防止出现09这样的情况
|
||||||
|
if (i>=start){
|
||||||
|
res.append('9');
|
||||||
|
}else res.append(chars[i]);
|
||||||
|
}
|
||||||
|
return Integer.parseInt(res.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
Reference in New Issue
Block a user