-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
65 lines (63 loc) · 2.06 KB
/
Solution.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public:
vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {
auto f = [](vector<int>& nums, int k) {
int n = nums.size();
vector<int> stk(k);
int top = -1;
int remain = n - k;
for (int x : nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
};
function<bool(vector<int>&, vector<int>&, int, int)> compare = [&](vector<int>& nums1, vector<int>& nums2, int i, int j) -> bool {
if (i >= nums1.size()) {
return false;
}
if (j >= nums2.size()) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
};
auto merge = [&](vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size(), n = nums2.size();
int i = 0, j = 0;
vector<int> ans(m + n);
for (int k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
};
int m = nums1.size(), n = nums2.size();
int l = max(0, k - n), r = min(k, m);
vector<int> ans(k);
for (int x = l; x <= r; ++x) {
vector<int> arr1 = f(nums1, x);
vector<int> arr2 = f(nums2, k - x);
vector<int> arr = merge(arr1, arr2);
if (ans < arr) {
ans = move(arr);
}
}
return ans;
}
};