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

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

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
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;
}

  

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

上一篇:Codeforces Round #224 (Div. 2)


下一篇:基础练习-2