Given an integer array
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence
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
Solution
如果這題沒有限制 k,那麼就用一個 stack 來解題就可
但有了k這個限制後,就必須考量當要把數字從stack拿出來的時候
剩下的數字還夠不夠滿足k這個條件
所以必須動態檢查 nums.size - i + stack.size > k 這個條件
kotlin(參考解答)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun mostCompetitive(nums: IntArray, k: Int): IntArray { | |
val stack = mutableListOf<Int>() | |
for(i in nums.indices) { | |
while(stack.isNotEmpty() && nums[i] < stack.last() && nums.size - i + stack.size > k) { | |
stack.removeAt(stack.lastIndex) | |
} | |
if(stack.size < k) { | |
stack.add(nums[i]) | |
} | |
} | |
return stack.toIntArray() | |
} | |
} |
沒有留言:
張貼留言