File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -127,6 +127,7 @@ public:
127
127
128
128
Java:
129
129
``` java
130
+ 版本1
130
131
class Solution {
131
132
public int monotoneIncreasingDigits (int N ) {
132
133
String [] strings = (N + " " ). split(" " );
@@ -144,6 +145,31 @@ class Solution {
144
145
}
145
146
}
146
147
```
148
+ java版本1中创建了String数组,多次使用Integer.parseInt了方法,这导致不管是耗时还是空间占用都非常高,用时12ms,下面提供一个版本在char数组上原地修改,用时1ms的版本
149
+ ``` java
150
+ 版本2
151
+ class Solution {
152
+ public int monotoneIncreasingDigits (int n ) {
153
+ if (n== 0 )return 0 ;
154
+ char [] chars= Integer . toString(n). toCharArray();
155
+ int start= Integer . MAX_VALUE ;// start初始值设为最大值,这是为了防止当数字本身是单调递增时,没有一位数字需要改成9的情况
156
+ for (int i= chars. length- 1 ;i> 0 ;i-- ){
157
+ if (chars[i]< chars[i- 1 ]){
158
+ chars[i- 1 ]-- ;
159
+ start= i;
160
+ }
161
+ }
162
+ StringBuilder res= new StringBuilder ();
163
+ for (int i= 0 ;i< chars. length;i++ ){
164
+ if (chars[i]== ' 0' && i== 0 )continue ;// 防止出现09这样的情况
165
+ if (i>= start){
166
+ res. append(' 9' );
167
+ }else res. append(chars[i]);
168
+ }
169
+ return Integer . parseInt(res. toString());
170
+ }
171
+ }
172
+ ```
147
173
148
174
149
175
Python:
You can’t perform that action at this time.
0 commit comments