leetcode 402题
农行软开的笔试题
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.递归的方法超时了?????
class Solution {
private int getMin(int[]arr,int n,int k){ //这里的n代表的是索引,
if(k==0) return 0; //表示的是不选任何数了
if(n == k-1){ //这里要组成一个数,现在就剩下,arr[0..n].length = k,直接组装成一个整数
int value=0;
for(int i = 0;i<k;i++){
value = (value + arr[i])*10;
}
value = value /10;
return value;
}
int minValue = getMin(arr,n-1,k); //这里不包含,arr[n],
minValue = Math.min(minValue,getMin(arr,n-1,k-1)*10 + arr[n]); //包含arr[n]
return minValue;
}
public String removeKdigits(String num, int k) {
int n = num.length();
if(k>n)return "0";
char[] chararr = num.toCharArray();
int[] arr = new int[n];
for(int i =0;i<n;i++){
arr[i]=Integer.parseInt(String.valueOf(chararr[i]));
}
return Integer.toString(getMin(arr,n-1,n-k));
}
}
动态规划的方法超内存了?????
class Solution {
public String removeKdigits(String num, int k){
int n = num.length();
if(k>n)return "0";
char[] chararr = num.toCharArray();
int[] arr = new int[n];
for(int i =0;i<n;i++){
arr[i]=Integer.parseInt(String.valueOf(chararr[i]));
}
int l = n-k;
if(l == 0)return "0";
int[][] memo = new int[n][l+1];
for(int i = 0;i<n;i++){
int tempMin = arr[0];
for(int j = 0;j<=i;j++){ //进行初始化赋值
if(tempMin>arr[j]){
tempMin = arr[j];
}
}
memo[i][1]=tempMin;
}
for(int i = 0;i<n;i++){
for(int j =2;j<=l;j++){
if(i+1<j)continue;
if(i+1==j){
int value = 0;
for(int m = 0;m<j;m++){
value = (value+arr[m])*10;
}
value = value /10;
memo[i][j] = value;
}else{
memo[i][j] = Math.min(memo[i-1][j],memo[i-1][j-1]*10+arr[i]);
}
}
}
return Integer.toString(memo[n-1][l]);
}
}