zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    第十五讲 实例模式
    第十四讲 实例模式
    将博客搬至CSDN
    CSU 1616: Heaps(区间DP)
    hdu 1281棋盘游戏(二分匹配)
    hdu 1042 N!(大数的阶乘)
    hdu 3371 Connect the Cities (最小生成树Prim)
    hdu 4502吉哥系列故事——临时工计划 (简单DP)
    hdu1230火星A+B (大数题)
    hdu1301 Jungle Roads (Prim)
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14078118.html
Copyright © 2011-2022 走看看