182. Delete Digits
- 本题难度: Medium
- Topic: Greedy
Description
Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.
Find the smallest integer after remove k digits.
N <= 240 and k <= N,
Example
Given an integer A = "178542", k = 4
return a string "12"
我的代码
class Solution:
"""
@param A: A positive integer which has N digits, A is a string
@param k: Remove k digits
@return: A string
"""
def DeleteDigits(self, A, k):
while(k>0):
l = len(A)
k = k-1
for i in range(1,l):
if A[i-1]>A[i]:
A = str(int(A[:i-1]+A[i:]))
break
if i == l-1:
A = str(int(A[:-1]))
return A
思路
当删除的元素比后一个与小的时候,不如直接删除最后一个元素。
在删除元素比后一个元素大的情况下,删除前面的元素肯定比删除后面元素带来的利益大。
- 时间复杂度 O(n*k)