[InterviewBit] Set Intersection

Set Intersection

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int Solution::setIntersection(vector<vector<int>> &A) {
sort(begin(A), end(A), [](auto& a, auto& b) {
if(a[1] != b[1]) return a[1] < b[1];
return a[0] > b[0];
});
int res = 2, mi = A[0][1] - 1, ma = A[0][1];
for(int i = 1; i < A.size(); i++) {
int l = A[i][0], r = A[i][1];
if(ma < l) {
res += 2;
ma = r, mi = r - 1;
} else if(ma == l) {
res += 1;
mi = ma, ma = r;
} else if(mi < l) {
res += 1;
if(ma == r) mi = ma - 1;
else mi = ma, ma = r;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/17/PS/interviewbit/set-intersection/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.