[LeetCode] 1673. 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.

Example 2:

Input: nums = [2,4,3,3,5,4,9,6], k = 4
Output: [2,3,3,4]

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 1 <= k <= nums.length

找出最具竞争力的子序列。

给你一个整数数组 nums 和一个正整数 k ,返回长度为 k 且最具 竞争力 的 nums 子序列。

数组的子序列是从数组中删除一些元素(可能不删除元素)得到的序列。

在子序列 a 和子序列 b 第一个不相同的位置上,如果 a 中的数字小于 b 中对应的数字,那么我们称子序列 a 比子序列 b(相同长度下)更具 竞争力 。 例如,[1,3,4] 比 [1,3,5] 更具竞争力,在第一个不相同的位置,也就是最后一个位置上, 4 小于 5 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-most-competitive-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是单调栈。题意是寻找一个长度为 K 的子序列且需要确保竞争力尽可能大,但是我第一次做的时候只是一味地照顾到了竞争力(栈中元素单调增)而没有照顾到栈中元素的个数,所以导致了有几个 test case 最后生成的子序列的长度不足 K。

这道题我们做的时候跟一般的单调栈的题目稍微有一些区别。总体思路还是单调栈,但是在遍历 input 数组的过程中,我们不光要保持栈中的元素单调增,同时栈中元素个数 + 剩下未遍历的元素个数需要一直大于 K,如果不满足则不能从栈中弹出元素了,否则会导致最后的子序列中元素个数不足 K 个。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int[] mostCompetitive(int[] nums, int k) {
 3         int len = nums.length;
 4         Deque<Integer> queue = new ArrayDeque<>();
 5         for (int i = 0; i < nums.length; i++) {
 6             // len - i + queue.size() > k
 7             // 数组长度 - 目前处理的个数 = 还未处理到的个数
 8             // 还未处理到的个数 + 已经在queue中的个数 > k,才能pop,否则会导致不足K个
 9             while (!queue.isEmpty() && nums[i] < queue.peekLast() && len - i + queue.size() > k) {
10                 queue.pollLast();
11             }
12             if (queue.size() < k) {
13                 queue.offer(nums[i]);
14             }
15         }
16         
17         int[] res = new int[queue.size()];
18         for (int i = 0; i < res.length; i++) {
19             res[i] = queue.pollFirst();
20         }
21         return res;
22     }
23 }

 

单调栈相关题目

LeetCode 题目总结

posted @ 2021-03-09 01:03  CNoodle  阅读(269)  评论(0编辑  收藏  举报