这次还是贪婪算法的题啦:Remove K Digits
402 | Remove K Digits | 26.1% | Medium |
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.
在一个数字串中删去k个数字,找到最小的那个数。
算法的原理是这样的:每次删去一个数字,每次删去的数字都是原来的数字串中第一个比后一位大的数,这样循环k次,得到的数就是题目所要求的。
当然有一些特殊情况,比如原来的数字就只有k位,那结果就是0了;如果k=0,那就返回原数字串;如果循环中出现数字从左到右都是递增,也就是不存在数字位比后一位大的情况,那么这种情况下我们所要做的就是删除数字串中的最后一位,比如1234,我们就需要依次删去4,3,2,1。
上代码:
string removeKdigits(string& num, int k)
{
if(k==0)
{
while(num[0]=='0')
{
num.erase(0,1);
}
if(num.length()==0)
{
return "0";
}
return num;
}
if(num.length()==1)
{
if(k==0)
{
return num;
}
else if(k==1)
{
return "0";
}
}
for(int i=0;i<k;i++)
{
if(num.length()==1)
{
num.erase(0,1);
}
else
{
for(int j=0;j<num.length()-1;j++)
{
if(num[j]>num[j+1])
{
num.erase(j,1);
//cout<<"num="<<num<<endl;
break;
}
else if(j==num.length()-2&&num[j]<=num[j+1])
{
num.erase(j+1,1);
//cout<<"num="<<num<<endl;
break;
}
}
}
}
while(num[0]=='0')
{
num.erase(0,1);
}
if(num.length()==0)
{
return "0";
}
return num;
}
这里为了直接利用输入的字符串所以把题目的输入稍稍改了一下,加了个&,用了一下引用
结果嘛
33 / 33 test cases passed.
Runtime:
13 ms