例如,对于号码9511145
,如果我想从此号码中删除3位数,则最大号码为9545
。删除的数字不必是连续的。但是,剩余数字的相对位置应保持不变。数字可以是10 6 位数。为了在迭代方法中解决这个问题,可能需要O(N 2 )时间。如果有人可以建议任何更好的方法来解决这个问题那么这将是一个很大的帮助。
答案 0 :(得分:0)
这个问题的解决方案得到了很好的回答here。 唯一的区别是你必须保持堆栈的排序递减。
# process digits from left to right
for each digit from left to right
if digit <= top of the stack
push(digit)
continue
while (digit > top of the stack) and (we have enough digits to reach n-k digits)
pop()
push(digit)
pop extra digits
9511145
push(9) => 9
push(5) because 5 <= 9 => 95
push(1) because 1 <= 5 => 951
push(1) because 1 <= 1 => 9511
push(1) because 1 <= 1 => 95111
pop() because 4 > 1 and we can still end up with 4 digits => 9511
pop() because 4 > 1 and we can still end up with 4 digits => 951
pop() because 4 > 1 and we can still end up with 4 digits => 95
push(4) because 4 <= 5 => 954
push(5) because we need to have 4 digits at least => 9545