-
Notifications
You must be signed in to change notification settings - Fork 0
/
349.txt
86 lines (39 loc) · 1.63 KB
/
349.txt
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
1.O(n), O(N);
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if (nums1.empty() || nums2.empty()) return {};
unordered_set<int> set(nums1.begin(),nums1.end());
vector<int> result;
for (int num :nums2){
if (set.count(num)>0){
result.push_back(num);
set.erase(num);
}
}
return result;
}
};
2. O£¨nlogn£© O£¨1£©£»
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
if (nums1.empty() || nums2.empty()) return {};
vector<int> result ;
int i = 0 , j = 0;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
while ( i <nums1.size() && j <nums2.size()){
if (nums1[i] < nums2[j]) i++;
else if (nums1[i] > nums2[j]) j++ ;
else{
if (result.empty() || result.back() != nums1[i]){
result.push_back(nums1[i]);
}
i++;
j++;
}
}
return result;
}
};