[LeetCode] 402. Remove K Digits Java
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] 402. Remove K Digits Java
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
?
Given a non-negative integer?num?represented as a string, remove?k?digits from the number so that the new number is the smallest possible.
Note:
- The length of?num?is less than 10002 and will be ≥?k.
- The given?num?does not contain any leading zero.
Example 1:
Input: num = "1432219", k = 3 Output: "1219" Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.Example 2:
Input: num = "10200", k = 1 Output: "200" Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.Example 3:
Input: num = "10", k = 2 Output: "0" Explanation: Remove all the digits from the number and it is left with nothing which is 0.?題意及分析:有一個N為長的數字,用字符串來代替了,現在要求你將它刪除K位,使得其得到的結果最小。對于每次刪除的情況有兩種
(1)假如第一個數不為0,第二個數為0,那么我們刪除第一個數,就相當于數量級減少2,這樣比刪除得到的數其他任何一個方法都小
(2)另一種情況,我們找到第一次遍歷的局部最大值,即遍歷num第一個滿足num.charAt(i)>num.charAt(i+1)的值,刪除這個點,得到的值最小。這里就是貪心算法,每次刪除一個局部最大
代碼:
public class Solution {public String removeKdigits(String num, int k) {int n=0;while(true){n =num.length();if(n <= k || n == 0) return "0";if(k-- == 0){// System.out.println(num);return num;};if(num.charAt(1)=='0'){ //第二位數為0,則刪除前面一位數int firstNotZero = 1;while(firstNotZero<n&&num.charAt(firstNotZero)=='0') firstNotZero++;num=num.substring(firstNotZero);}else{ //不然尋找第一個下降的數int i=0;while(i<n-1){if(num.charAt(i)>num.charAt(i+1)){num=num.substring(0, i)+num.substring(i+1);break;}elsei++;}if(i==n-1) num=num.substring(0, i);}}} }?
?
?
?
Seen this question in a real interview before??
?
轉載于:https://www.cnblogs.com/271934Liao/p/7083544.html
總結
以上是生活随笔為你收集整理的[LeetCode] 402. Remove K Digits Java的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 近视眼做手术有用吗(近视眼做手术好吗)
- 下一篇: 老骥伏枥志在千里 烈士暮年壮心不已(ld