[LeetCode] Intersection of Multiple Arrays

2248. Intersection of Multiple Arrays

Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.

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
#define all(a) begin(a), end(a)
using namespace std;

class Solution {
pair<bool, int> eq(vector<vector<int>>& nums, vector<int>& pos) {
int target = nums[0][pos[0]];
for(int i = 0; i < pos.size(); i++)
if(target != nums[i][pos[i]]) {
return {false, i};
}
return {true, -1};
}
public:
vector<int> intersection(vector<vector<int>>& nums) {
vector<int> res;
int n = nums.size();
vector<int> pos(n, 0);
for(auto& n : nums)
sort(all(n));
bool eof = false;
while(!eof) {
auto [pb, po] = eq(nums,pos);
if(pb) {
res.push_back(nums[0][pos[0]]);
for(int i = 0; i < pos.size(); i++) {
if(++pos[i] == nums[i].size()) eof = true;
}
} else {
int req = max(nums[0][pos[0]], nums[po][pos[po]]);
for(int i = 0; i < pos.size(); i++) {
while(!eof and nums[i][pos[i]] < req) {
if(++pos[i] == nums[i].size())
eof = true;
}
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/24/PS/LeetCode/intersection-of-multiple-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.