【Leetcode】1673. Find the Most Competitive Subsequence
題目地址:
https://leetcode.com/problems/find-the-most-competitive-subsequence/
給定一個陣列 A A A,求其字典序最小的長 k k k的子序列。
思路是單調棧。求長 k k k的子序列相當於在 A A A裡刪掉 l A − k l_A-k lA−k個數字。我們用一個變數 r r r標記還可以刪多少個數字,一開始賦值為 l A − k l_A-k lA−k。接著開一個從棧底到棧頂嚴格單調上升的棧,如果棧非空並且棧頂大於新來的數,並且還能刪數字(指 r > 0 r>0 r>0成立),則出棧,並將 r r r減 1 1 1,直到棧空或者棧頂小於等於新來的數或者 r = 0 r=0 r=0(這時沒法刪了),接著將新來的數入棧(如果棧滿,說明新來的數無法入棧,則多刪一個數,將 r r r減去 1 1 1)。最後棧底到棧頂的陣列即為所求。演算法正確性證明,只需要注意每次可以刪的時候(這裡的刪主要指的是pop棧頂),刪總是比不刪好。程式碼如下:
public class Solution {
public int[] mostCompetitive(int[] nums, int k) {
int[] res = new int[k];
int idx = 0, rem = nums.length - k;
for (int i = 0; i < nums.length; i++) {
// 如果棧非空並且棧頂大於新來的數,並且還能刪數字,則出棧
while (idx > 0 && res[idx - 1] > nums[i] && rem > 0) {
idx--;
rem--;
}
if (idx < res.length ) {
res[idx++] = nums[i];
} else {
rem--;
}
}
return res;
}
}
時間複雜度 O ( l A ) O(l_A) O(lA),空間 O ( 1 ) O(1) O(1)。
相關文章
- LeetCode #392: Is SubsequenceLeetCode
- leetcode392. Is SubsequenceLeetCode
- Leetcode: Arithmetic Slices II - SubsequenceLeetCode
- LeetCode-Wiggle SubsequenceLeetCode
- LeetCode-Longest Increasing SubsequenceLeetCode
- LeetCode-Increasing Triplet SubsequenceLeetCode
- leetcode Container With Most WaterLeetCodeAI
- [LeetCode] 727. Minimum Window SubsequenceLeetCode
- 【LeetCode】Increasing Triplet Subsequence(334)LeetCode
- Leetcode 11 Container With Most WaterLeetCodeAI
- Leetcode-Container With Most WaterLeetCodeAI
- Container With Most Water leetcode javaAILeetCodeJava
- leetcode_11. Container With Most WaterLeetCodeAI
- LeetCode 11. Container With Most WaterLeetCodeAI
- [LeetCode] 674. Longest Continuous Increasing SubsequenceLeetCode
- 【Leetcode】1081. Smallest Subsequence of Distinct CharactersLeetCode
- LeetCode - Medium - 11. Container With Most WaterLeetCodeAI
- [LeetCode] Find the Duplicate NumberLeetCode
- LeetCode-Find the CelebrityLeetCode
- Find Peak element leetcodeLeetCode
- LeetCode-Longest Substring with At Most K Distinct CharactersLeetCode
- LeetCode 389. Find the DifferenceLeetCode
- LeetCode-Find the Duplicate NumberLeetCode
- Leetcode-Find Peak ElementLeetCode
- Leetcode-Longest Substring with At Most Two Distinct Characters.LeetCode
- [LeetCode] Container With Most Water 裝最多水的容器LeetCodeAI
- [LeetCode] 2070. Most Beautiful Item for Each QueryLeetCode
- [LeetCode] 277. Find the CelebrityLeetCode
- [LeetCode] 724. Find Pivot IndexLeetCodeIndex
- [leetcode] 890. Find and Replace PatternLeetCode
- leetcode287: Find the Duplicate NumberLeetCode
- LeetCode Container With Most Water(011)解法總結LeetCodeAI
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- Leetcode 442. Find All Duplicates in an ArrayLeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- LeetCode-Find K Pairs with Smallest SumsLeetCodeAI
- LeetCode 題解(252) : Find the Duplicate NumberLeetCode
- LeetCode C++ 376. Wiggle Subsequence【Dynamic Programming】中等LeetCodeC++