[itint5]两有序数组的交和并

时间:2024-07-31 19:33:44

这一题也简单,唯一有意思的地方是提炼了一个函数用来做数组索引去重前进。

int forward(vector<int> &arr, int i) {
while (i+1 < arr.size() && arr[i] == arr[i+1]) i++;
i++;
return i;
} vector<int> arrayUnion(vector<int> &a, vector<int> &b) {
vector<int> ans;
int i = 0;
int j = 0;
while (i < a.size() && j < b.size()) {
if (a[i] == b[j]) {
ans.push_back(a[i]);
i = forward(a, i);
j = forward(b, j);
} else if (a[i] < b[j]) {
ans.push_back(a[i]);
i = forward(a, i);
} else {
ans.push_back(b[j]);
j = forward(b, j);
}
}
while (i < a.size()) {
ans.push_back(a[i]);
i = forward(a, i);
}
while (j < b.size()) {
ans.push_back(b[j]);
j = forward(b, j);
}
return ans;
} vector<int> arrayIntersect(vector<int> &a, vector<int> &b) {
vector<int> ans;
int i = 0;
int j = 0;
while (i < a.size() && j < b.size()) {
if (a[i] == b[j]) {
ans.push_back(a[i]);
i = forward(a, i);
j = forward(b, j);
} else if (a[i] < b[j]) {
i = forward(a, i);
} else {
j = forward(b, j);
}
}
return ans;
}