Remove K Digits
来源:互联网 发布:刀塔传奇数据库 编辑:程序博客网 时间:2024/06/09 22:35
problem 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.
要使得删除k位后的数字之最小,首位数字应该是前k+1中最小的那个,设该位置的下一位为temp,k++,则删除后的第二位数字应该是temp位到k+1位中最小的那个,以此类推,直到k=length。该算法是贪婪算法,每次从temp到k+1之间选择最小的。算法复杂度为o(kn)。
代码如下:class Solution {public: string removeKdigits(string num, int k) { int len=num.length(); int temp,i,j; char t; string result(len-k,'0'); t=num[0]; temp=0;j=0;if(k==len){ string res(1,'0'); return res;} else { while(k<len) { t=num[temp]; temp++; for(i=temp;i<k+1;i++) { if(num[i]<t) { t=num[i]; temp=i+1; } } result[j]=t; j++; k++; } //cout<<result<<endl; i=0; while(result[i]=='0'&&(i+1)<result.length()) { result=result.erase(i,1); } cout<<result; return result; } }};
0 0
- 402. Remove K Digits
- 402. Remove K Digits
- 402.Remove K Digits
- 402. Remove K Digits
- Leetode402. Remove K Digits
- Remove K Digits
- [LeetCode402]Remove K Digits
- 402. Remove K Digits
- LeetCode: Remove K Digits
- [Medium]Remove K Digits
- 402. Remove K Digits
- 402. Remove K Digits
- 402. Remove K Digits
- Remove K Digits
- Remove K Digits
- [LeetCode]Remove K Digits
- leetcode:Remove K Digits
- 402. Remove K Digits
- react中function()报错?
- 【设计模式】单例模式(Singleton)
- UVA
- 浅谈——Java中接口类与抽象类
- python request 字符集设置
- Remove K Digits
- Android Filter ListView, RecyclerView
- 配置ctags
- Uva 400
- 基于Spark实现随机森林代码
- 2017腾讯-暑期实习生在线测试-16进制字符串转换
- 单点登录之cas4.2.7服务端数据库配置(读数据库验证用户并对密码进行加密)
- 桶排序
- 算法训练 纪念品分组