|
1 |
| -typedef pair<int,int> p; |
| 1 | +// Runtime: 9 ms (Top 29.13%) | Memory: 9.60 MB (Top 91.68%) |
| 2 | + |
| 3 | +// OJ: https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/ |
| 4 | +// Author: github.com/lzl124631x |
| 5 | +// Time: O(NlogN) |
| 6 | +// Space: O(N) |
2 | 7 | class Solution {
|
3 | 8 | public:
|
4 |
| - vector<int> maxSubsequence(vector<int>& nums, int k) { |
5 |
| - // Heap 'q' will store the k largest elements of the array |
6 |
| - // The following heap is of pair where first element of pair is the element and the second element is the corresponding index |
7 |
| - // That's how in queue sorting will be done according to the array element |
8 |
| - priority_queue<p,vector<p>,greater<p>>q; |
9 |
| - for(int i=0;i<nums.size();i++) |
10 |
| - { |
11 |
| - q.push({nums[i],i}); |
12 |
| - if(q.size()>k) |
13 |
| - { |
14 |
| - q.pop(); |
15 |
| - } |
16 |
| - } |
17 |
| - |
18 |
| - // heap 'aux' will sort the elements based on their index |
19 |
| - // sorting according to the index is necessary in order get the original order of the elements |
20 |
| - // in the following heap the first element of the pair is the index and the second element is the array element itself |
21 |
| - priority_queue<p,vector<p>,greater<p>>aux; |
22 |
| - while(!q.empty()) |
23 |
| - { |
24 |
| - aux.push({q.top().second,q.top().first}); |
25 |
| - q.pop(); |
26 |
| - } |
27 |
| - |
28 |
| - // once the elements are sorted according to their indices , push them in a vector |
29 |
| - vector<int>ans; |
30 |
| - while(!aux.empty()) |
31 |
| - { |
32 |
| - ans.push_back(aux.top().second); |
33 |
| - aux.pop(); |
34 |
| - } |
35 |
| - |
36 |
| - // finally return the answer |
| 9 | + vector<int> maxSubsequence(vector<int>& A, int k) { |
| 10 | + vector<int> id(A.size()); |
| 11 | + iota(begin(id), end(id), 0); // Index array 0, 1, 2, ... |
| 12 | + sort(begin(id), end(id), [&](int a, int b) { return A[a] > A[b]; }); // Sort the indexes in descending order of their corresponding values in `A` |
| 13 | + id.resize(k); // Only keep the first `k` indexes with the greatest `A` values |
| 14 | + sort(begin(id), end(id)); // Sort indexes in ascending order |
| 15 | + vector<int> ans; |
| 16 | + for (int i : id) ans.push_back(A[i]); |
37 | 17 | return ans;
|
38 | 18 | }
|
39 | 19 | };
|
0 commit comments