How to get the least number after deleting k digits from the input number

前端 未结 11 1217
灰色年华
灰色年华 2020-12-11 05:34

For example, if the input number is 24635, the least number is 23 after deleting any 3 digits.

It\'s not the same as taking the two smalles

11条回答
  •  臣服心动
    2020-12-11 05:45

    Deleting k digits means keeping n - k digits, where n is the total number of digits.

    Use a stack that you keep sorted ascendingly. You remove elements from it as long as you can still make it to n - k digits and your current element is smaller than the top of the stack:

    push(2) => 2
    push(4) because 2 < 4 => 24
    push(6) because 4 < 6 => 246
    pop() because 3 < 6 and we can still end up with 2 digits => 24
    pop() for the same reason => 2
    push(3) => 23
    push(5) => 235
    

    Then just take the first k digits => 23. Or you can make sure never to push more than k digits, and then the final stack is your solution.

    Note that you cannot pop elements if that means you will not be able to build a solution of k digits. For this, you need to check the current number of elements in the stack and the number of digits to the right of your current position on the input number.

    Pseudocode:

    stack = []
    for each d in digits:
      while !stack.empty() and d < stack.top() and (*):
        stack.pop()
    
      if stack.size() < n - k:
        stack.push(d)
    
     (*) - exercise, fill in the condition that prevents you 
           from popping elements if you still want to be able to get to a solution.
     Hint: count how many elements the for loop went over already
           and see how many are left. Also consider how many you have left in the stack.
    

    Since each element enters and leaves the stack at most once, the complexity is O(n).

提交回复
热议问题