【第七周】402. Remove K Digits

来源:互联网 发布:linux的vim配置文件 编辑:程序博客网 时间:2024/06/03 22:11

原题:

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.

 leetcode地址:https://leetcode.com/problems/remove-k-digits/description/


解题思路

 题目大意:从一个长度为n的数串中删去k位数,求出删去后的新数串的最小值。

 如何求解呢?我这里想到了两种思路。

 首先从删去数位的角度考虑:很明显可以看出来,删去大数一般比删去小数要好;删去高位数一般比删去低位数要好。当k=1,即我们只需要删除1位数的时候,删去哪位呢?我们可以从高位向低位遍历:令最高位为第i=0位;从最高位开始,当第n位>第n+1位时,则删去第n位。很容易可以验证,这时数串肯定是最小值。
 然后我们可以利用贪心算法的思想:当要删去k个数时,就把以上过程重复k遍,最后得到的数串肯定是最小的。因为每一个删除是互不影响的;而且每一个删除都是局部最优解,通过一系列局部最优解是可以得到整体最优解的。有了清晰的思路,代码就很容易实现了。

 然后是第二种思路:从剩余的数位角度考虑。数串有n位,要删去k位,则删去后的数串为n-k位。有什么样的方法可以直接获取到最优解的数串呢?

 首先考虑特殊情况:当k=0时,最优解为原数串;当k=n时,最优解为数串“0”。

 当k小于n时:在数串最高的k+1位中,找到值最小的那一位,假设为第t位。那么,在t位之前的所有数位是肯定可以删除的。为什么?因为最高位的值越小越好。无论怎么删除,最优解的最高位肯定是在这k+1位之中;所以我们选这k+1位中的最小值作为最优解的最高位,是一定正确的。
 经过这一步操作,最优解的最高位已经确定了;我们也删去了t-1个数,剩下只需要删去k-(t-1)个数了。那么,接下来的问题就是在由第t+1位开始的子串中,删去k-(t-1)个数了;我们就可以利用同样的思路继续删除,直到删完k个数为止。
 这里同样也利用了贪心算法的思想;通过局部最优来构建整体最优解。

 这两种算法效率并不算高;不过思路还是比较好理解。


代码

 给出的是方案二的代码。

class Solution {public:    string removeKdigits(string num, int k) {            if (k == 0) return num;        // 特殊情况处理,        if (k == num.length()) return "0";        string ret = solution(num, k);    //获取最优解        int pos = 0;                //前导零的清除        for (int i = 0; i < ret.length(); i++) {            if (ret[i] != '0') break;            pos++;        }        ret = ret.substr(pos, ret.length()- pos);        if (ret == "") ret = "0";        return ret;    }    int getMin(string str) {         //获取数串中最小值的位置        int ret = 0;        for (int i = 0; i < str.length(); i++) {            if (str[i] < str[ret]) {                ret = i;            }        }        return ret;    }    string solution(string num, int k) {       //最优解算法        if (k == 0) return num;        if (k == num.length()) return "";        string temp = num.substr(0, k+1);        int pos = getMin(temp);        return num[pos] + solution(num.substr(pos+1, num.length()-pos-1), k - pos);    }};

总结

 1、贪心算法的设计思想与基本要素
 2、数串的处理

原创粉丝点击