1673. Find the Most Competitive Subsequence

package LeetCode_1673

import java.util.*

/**
 * 1673. Find the Most Competitive Subsequence
 * https://leetcode.com/problems/find-the-most-competitive-subsequence/
 * Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ,
subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.

Example 1:
Input: nums = [3,5,2,6], k = 2
Output: [2,6]
Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
 * */
class Solution {
    /*
    * solution: Stack,scan each number, check current num if large than then the first one in stack,
    * pop the large one, keep the increasing stack;
    * Time:O(n), Space:O(n)
    * */
    fun mostCompetitive(nums: IntArray, k: Int): IntArray {
        var needRemoveCount = nums.size - k
        val stack = Stack<Int>()
        for (i in nums.indices) {
            while (stack.isNotEmpty() && nums[i] < stack.peek() && needRemoveCount > 0) {
                stack.pop()
                needRemoveCount--
            }
            stack.push(nums[i])
        }
        //handle case some case, for example 1111
        while (needRemoveCount > 0) {
            stack.pop()
            needRemoveCount--
        }
        val result = IntArray(k)
        var index = k - 1
        //replace element from right to left,so no need to reverse
        while (stack.isNotEmpty()) {
            result[index--] = stack.pop()
        }
        return result
    }
}

 

posted @ 2020-12-03 10:27  johnny_zhao  阅读(173)  评论(0编辑  收藏  举报