1. 程式人生 > >008-演算法面試必備-Remove K Digits(待修改)

008-演算法面試必備-Remove K Digits(待修改)

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]);
    }
}