- 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。
Set技术特点:Set中存放的是对象的引用,并且没有重复对象。Set接口主要实现了两个实现类:
• HashSet: HashSet类按照哈希算法来存取集合中的对象,存取速度比较快。
• TreeSet :TreeSet类实现了SortedSet接口,能够对集合中的对象进行排序。
Example:
Set set=new HashSet();
String s1=new String(“hello”);
String s2=s1;
String s3=new String(“world”);
Set.add(s1);
Set.add(s2);
Set.add(s3);
System.out.println(set.size()); //打印集合中对象引用的数目,结果为2.(set中没有重复对象,所以s1,s2只能有一个)
Solution:
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int len1=nums1.length, len2=nums2.length;
Set<Integer> set=new HashSet<Integer>();
Set<Integer> interSet=new HashSet<Integer>();
for(int i=0; i<len1; i++){
set.add(nums1[i]);
}
for(int i=0; i<len2; i++){
if(set.contains(nums2[i])) interSet.add(nums2[i]);
}
int[] ret=new int[interSet.size()];
int cnt=0;
for(int num:interSet){
ret[cnt++]=num;
} //for的一种遍历方式,通常用来遍历数组
return ret;
}
}
for (循环变量类型 循环变量名称 : 要被遍历的对象) 循环体
example:
/* 建立一个数组 */
int[] integers = {1, 2, 3, 4};
/* 开始遍历 */
for (int i : integers) {
System.out.println(i); //依次输出“1”、“2”、“3”、“4”。
}
利用hashset, 时间复杂度为O(n)。
方法2:利用两个指针
public class Solution {
public int[] intersection(int[] nums1; int[] nums2) {
Set<Integer> set=new Hash<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i=0;
int j=0;
while (i<nums1.length&&j<nums2.length) {
if (nums1[i]<nums2[j]) {
i++;
}
else if (nums1[i]>nums2[j]) {
j++;
}
else {
set.add(nums[i]);
i++;
j++;
}
}
int[] result=new int[set.size()];
int k=0;
for (Integer num:set) {
result[k++]=num;
}
return result;
}
}
方法3 Binary search:
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (Integer num : nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int i = 0;
int[] result = new int[set.size()];
for (Integer num : set) {
result[i++] = num;
}
return result;
}
public boolean binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return true;
}
if (nums[mid] > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return false;
}
}