Leetcode 349:Intersection of Two Arrays
阿新 • • 發佈:2021-01-29
Leetcode 349:Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
說人話:
給定兩個陣列 nums,求兩個陣列的公共元素。
幾個要點:
- 結果中的元素不重複
- 元素順序無所謂
[法1] 暴力法
思路
考慮到結果中元素不重複
這個要求,就可以想到用 Set
了。直接雙層迴圈,將 num1 和 num2 相等的元素放到 Set
當中即可。
程式碼
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set set = new HashSet();
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] == nums2[j]){
set.add(nums1[i]);
break;
}
}
}
Iterator iterator = set.iterator();
int[] result = new int[set.size()];
int i = 0;
while (iterator.hasNext()){
int next = (int)iterator.next();
result[i] = next;
i++;
}
return result;
}
}
提交結果
程式碼分析
不考慮集合框架底層原理的話:
- 時間複雜度:O(nm)
- 空間複雜度:O(k),k 為 n 和 m 中 length 小的那個
[法2] 去掉雙層 for 迴圈
思路
直接用兩個 HashSet
,然後利用內建方法 contains()
來判斷重複元素,這樣更快。
程式碼
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set set1 = new HashSet();
Set set2 = new HashSet();
for (int num : nums1){
set1.add(num);
}
for (int num: nums2){
if (set1.contains(num)){
set2.add(num);
}
}
int[] result = new int[set2.size()];
int i = 0;
Iterator iterator = set2.iterator();
while (iterator.hasNext()){
result[i] = (int)iterator.next();
i++;
}
return result;
}
}
提交結果
程式碼分析
不考慮集合框架底層原理的話:
- 時間複雜度:O(k)
- 空間複雜度:O(k)