更多LeetCode题解
我的解法
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> res = {};
for (int i = 0; i < nums1.size(); i++) {
if (nums2.end() != find(nums2.begin(), nums2.end(), nums1[i]) && res.end() == find(res.begin(), res.end(), nums1[i])) {
res.push_back(nums1[i]);
}
}
return res;
}
};
降低时间复杂度
此题稍微改进一点的解法就是使用unordered_set
来降低时间复杂度,因为set
的读取是
O
(
1
)
O(1)
O(1)
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> set1, set2;
for (int num : nums1) {
set1.insert(num);
}
for (int num : nums2) {
set2.insert(num);
}
if (set1.size() < set2.size()) return set_intersection(set1, set2);
else return set_intersection(set2, set1);
}
vector<int> set_intersection(unordered_set<int>& set1, unordered_set<int>& set2) {
vector<int> res;
for (int num : set1) {
if (set2.count(num)) {
res.push_back(num);
}
}
return res;
}
};
其他语言参照
java
class Solution {
public int[] set_intersection(HashSet<Integer> set1, HashSet<Integer> set2) {
int [] output = new int[set1.size()];
int idx = 0;
for (Integer s : set1)
if (set2.contains(s)) output[idx++] = s;
return Arrays.copyOf(output, idx);
}
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (Integer n : nums1) set1.add(n);
HashSet<Integer> set2 = new HashSet<Integer>();
for (Integer n : nums2) set2.add(n);
if (set1.size() < set2.size()) return set_intersection(set1, set2);
else return set_intersection(set2, set1);
}
}
python
class Solution:
def set_intersection(self, set1, set2):
return [x for x in set1 if x in set2]
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
if len(set1) < len(set2):
return self.set_intersection(set1, set2)
else:
return self.set_intersection(set2, set1)
此外,java和python都有内置的方法来简化代码,分别如下
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (Integer n : nums1) set1.add(n);
HashSet<Integer> set2 = new HashSet<Integer>();
for (Integer n : nums2) set2.add(n);
set1.retainAll(set2);
int [] output = new int[set1.size()];
int idx = 0;
for (int s : set1) output[idx++] = s;
return output;
}
}
class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
set1 = set(nums1)
set2 = set(nums2)
return list(set2 & set1)