Remove K Digits

原题链接:https://leetcode.com/problems/remove-k-digits/description/

题目描述:
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.

样例:

  1. 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.

  2. 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.

  3. Example 3:

    Input: num = “10”, k = 2
    Output: “0”
    Explanation: Remove all thedigits from the number and it is left with nothing which is 0.

Solution: 我们可以采用贪心法的思路。举个例子,在第一个样例中,num = “1432219”, k = 3, 那么产生的结果应该是一个四位数。对于这个四位数的每一位,都有一个有限的选择范围,比如说,在此例子中,四位数的千位的范围只能是num[0~3],而百位只能从千位选择的数的下一位开始选,一直到num[4],当千位选择num[0]中的1时,那么百位的选择范围就是num[1~4]。依次类推,结果的每一个数位都有一个选择范围,我们只需要对每一个数位,都尽可能地在期选择范围内选择最小的数即可。

class Solution {
public:
    string trim(string num) {
        string result;
        bool flag = true;
        for (int i = 0; i < num.size(); ++i) 
            if (num[i] == '0' && flag) ;
            else {
                flag = false;
                result += num[i];
            }
        if (result.empty()) result = "0";
        return result;
    }

    string removeKdigits(string num, int k) {        
        string result = "";
        int size = num.size();

        int start_index = 0;
        int end_index;
        for (int i = 0; i < size - k; i++) {
            end_index = k + i;

            int j = start_index;
            int min_index = -1;
            char min_element = '9' + 1;
            while (j <= end_index) {
                if (num.at(j) < min_element) {
                    min_element = num.at(j);
                    min_index = j;
                }
                j++;
            }
            result += num[min_index];

            start_index = min_index + 1;
        }
        return trim(result);
    }
};

算法分析: 对一个n位数,产生的结果有n-k位,每一个数位的选择范围最大是k,所以复杂度大约有O(k*n)。

改进: Well, one can simply scan from left to right, and remove the first “peak” digit; the peak digit is larger than its right neighbor. One can repeat this procedure k times, and obtain the algorithm.

string removeKdigits(string num, int k) {
        string res;
        int keep = num.size() - k;
        for (int i=0; i<num.size(); i++) {
            while (res.size()>0 && res.back()>num[i] && k>0) {
                res.pop_back();
                k--;
            }
            res.push_back(num[i]);
        }
        res.erase(keep, string::npos);

        // trim leading zeros
        int s = 0;
        while (s<(int)res.size()-1 && res[s]=='0')  s++;
        res.erase(0, s);

        return res=="" ? "0" : res;
    }
在LeetCode第402题“Remove K Digits”中,你需要从一个非负整数的数组(表示为字符串形式)中移除k个数字,使得剩下的数字按顺序组成最小的非负整数。这里是一个简单的C语言解决方案: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // Function to find the minimum number after removing k digits char* removeKdigits(char* num, int k) { int n = strlen(num); if (k >= n) return ""; // Initialize a stack for storing indices int minStack[5] = {n}, top = 0; for (int i = 0; i < n; ++i) { while (top > 0 && num[i] < num[minStack[top - 1]]) { // Remove digit at index minStack[top - 1] num[minStack[top - 1]] = '\0'; --minStack[top--]; } // Push current index onto the stack if not full and still need to remove more digits if (k > 0 && num[i] != '0') { minStack[++top] = i; --k; } } // If all k digits removed or reached the beginning of the number if (k == 0) { num[minStack[0]] = '\0'; // Convert it back to an integer return num; } else { // Fill in the remaining positions with zeros memmove(num + 1, num + minStack[0] + 1, n - minStack[0]); num[0] = '0'; // Add a zero at the beginning return num; } } int main() { char* num = "1432219"; int k = 3; char* result = removeKdigits(num, k); printf("Minimum number after removing %d digits: %s\n", k, result); free(result); // Don't forget to free the dynamically allocated memory return 0; } ``` 在这个程序中,我们维护了一个栈,用于保存需要删除的小数字的索引。遍历输入字符串,每次遇到比栈顶元素小的数字,就将其后面的数字依次向前移动并删除。同时检查是否还有剩余的k值,如果有的话,继续将当前数字入栈。最后,根据剩余的k值处理结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值