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.
不能有重复数字,就想到使用数据类型Set。
逻辑原理:
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1==null || nums2==null)
return null;
if(nums1.length==0 || nums2.length==0)
return new int[0];
Set set=new HashSet();
for(int i=0;i res = new ArrayList();
for(int i=0;i
PS: 遍历HashSet
Iterator i=set.iterator();
while(i.hasNext()){
int temp=(int)i.next();
}
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
Follow up(答案在后面):
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1==null || nums2==null || nums1.length==0 || nums2.length==0)
return new int[]{};
Map map=new HashMap();
List list=new ArrayList();
for(int i=0;i
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List temp=new ArrayList();
List list=new ArrayList();
for(int x:nums1){
temp.add(x);
}
for(int x:nums2){
if(temp.contains(x)){//看源码可知contains的复杂度是O(temp.size())
list.add(x);
temp.remove((Integer)x);
}
}
int[]res=new int[list.size()];
for(int i=0;i
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);//底层使用了快排,O(nlogn)
Arrays.sort(nums2);
List list=new ArrayList();
for(int i=0,j=0;inums2[j]){
j++;
}else{
i++;
}
}
int[]res=new int[list.size()];
for(int i=0;i
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
问题