349的題目要求:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
- 總結方法:用到的知識點是hashset不允許存儲兩個一樣的元素,因爲即使nums1,nums2各自的元素有重複,輸出的始終是相同的一個,所以可以利用HashSet的特性。同時,還是用了set.contains(element) 和 set.add(element)的方法,另外還用到了for(<Element> e : array)的遍歷方法,數組的Arrays.sort(數組),set.size()獲取set大小,等函數。
O(n)
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> s = new HashSet<Integer>();
Set<Integer> intersect = new HashSet<Integer>();
//add mums1 numbers into set
for(int i=0;i<nums1.length;i++){
s.add(nums1[i]);
}
for(int i=0;i<nums2.length;i++){
if(s.contains(nums2[i])) intersect.add(nums2[i]);
}
int ans[] =new int[intersect.size()];
int i=0;
for(int number:intersect)
ans[i++] = number;
return ans;
}
}
第二種:O(nlogn)爲什麼呢???
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> intersect = new HashSet<Integer>();
int i=0,j=0;
Arrays.sort(nums1);
Arrays.sort(nums2);
while(i<nums1.length&&j<nums2.length){
if(nums1[i]<nums2[j]) i++;
else if(nums1[i]>nums2[j]) j++;
else{
intersect.add(nums1[i]);
i++;
j++;
}
}
int[] ans = new int[intersect.size()];
int m=0;
for(int numbers:intersect)
ans[m++] = numbers;
return ans;
}
}
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2, 2]
.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
- 總結:以爲需要輸出所有的相同的元素,那麼因此Set不可以被使用,因爲需要存儲相同的元素,這裏我使用了ArrayList來存儲intersection的部分,同時也用到了list.add(element) 和Arrays.sort(arr),list.size(). arraylist最好不要用contains,這個時候要用indexOf(element)來檢查是否含有某元素,如果返回-1則代表沒有。
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
ArrayList<Integer> intersect = new ArrayList<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i=0,j=0;
while(i<nums1.length&&j<nums2.length){
if(nums1[i]>nums2[j]) j++;
else if(nums1[i]<nums2[j]) i++;
else{
intersect.add(nums1[i]);
i++;
j++;
}
}
int[] ans = new int[intersect.size()];
int m=0;
for(int num:intersect) ans[m++] = num;
return ans;
}
}