From 0ab0d78698dd607dfb7f2f6a8ab36477e5c6db80 Mon Sep 17 00:00:00 2001 From: Manuel Pineda Date: Thu, 21 Jan 2021 20:37:09 +0100 Subject: [PATCH] [LeetCode] January 21. Kotlin implementation gives TLE. --- solved/LeetCode/Challenges/2020/January/21.cc | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 solved/LeetCode/Challenges/2020/January/21.cc diff --git a/solved/LeetCode/Challenges/2020/January/21.cc b/solved/LeetCode/Challenges/2020/January/21.cc new file mode 100644 index 00000000..15aaf24e --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/21.cc @@ -0,0 +1,54 @@ +class Solution { +public: + vector mostCompetitive(vector& nums, int k) { + auto ans = deque(); + auto need = [&ans, &k] () { + return k - ans.size(); + }; + ans.push_back(nums[0]); + for (int i = 1; i < nums.size(); i++) { + int rem = nums.size() - i; + if (nums[i] > ans.back()) { + if (ans.size() < k) { + ans.push_back(nums[i]); + } + continue; + } + while (ans.size() > 0 && nums[i] < ans.back() && rem > need()) { + ans.pop_back(); + } + if (ans.size() < k) { + ans.push_back(nums[i]); + } + } + return vector(ans.begin(), ans.end()); + } +}; + +/* +Kotlin code with TLE. + +class Solution { + fun mostCompetitive(nums: IntArray, k: Int): IntArray { + val ans = ArrayDeque(nums.size) + val need = { k - ans.size } + ans.addLast(nums[0]) + for (i in 1 until nums.size) { + val rem = nums.size - i + if (nums[i] > ans.last()) { + if (ans.size < k) { + ans.addLast(nums[i]) + } + continue + } + while (ans.size > 0 && nums[i] < ans.last() && rem > need()) { + ans.removeLast() + } + if (ans.size < k) { + ans.addLast(nums[i]) + } + } + return ans.toIntArray() + } +} +*/