-
Notifications
You must be signed in to change notification settings - Fork 3
/
2389.cpp
50 lines (46 loc) · 1.38 KB
/
2389.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
sort(nums.begin(), nums.end());
int n = nums.size();
int m = queries.size();
vector<int> res(m, 0);
for (int i = 0; i < m; ++i) {
int query = queries[i];
int curr = 0;
int index = 0;
while (index < n && curr <= query) {
curr += nums[index];
index++;
}
res[i] = index - 1;
if (curr <= query) res[i] = index;
}
return res;
}
};
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
int m = queries.size();
vector<int> res(m, 0);
sort(nums.begin(), nums.end());
int n = nums.size();
vector<pair<int, int>> queriesWithIdx(m, {0, 0});
for (int i = 0; i < m; ++i) {
queriesWithIdx[i].first = queries[i];
queriesWithIdx[i].second = i;
}
sort(queriesWithIdx.begin(), queriesWithIdx.end());
int index = 0;
int sum = 0;
for (auto& [query, idx] : queriesWithIdx) {
while (index < n && sum + nums[index] <= query) {
sum += nums[index];
index++;
}
res[idx] = index;
}
return res;
}
};