题目描述:
思路:第一种思路:直接用HashMap来进行。第二种思路:两个数组排序后,分别用两个指针挨个比较。
哈希表:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer,Integer> map=new HashMap();
for(int i=0;i<nums1.length;i++){
if(map.containsKey(nums1[i])){
int m=map.get(nums1[i])+1;
map.put(nums1[i],m);
}else{
map.put(nums1[i],1);
}
}
int[] tem=new int[nums1.length];
int index=0;
for(int i=0;i<nums2.length;i++){
if(map.containsKey(nums2[i])){
tem[index++]=nums2[i];
if(map.get(nums2[i])>1){
int n=map.get(nums2[i])-1;
map.put(nums2[i],n);
}else{
map.remove(nums2[i]);
}
}
}
int[] result=new int[index];
for(int i=0;i<index;i++){
result[i]=tem[i];
}
return result;
}
}
结果:
排序:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] tem=new int[nums1.length];
int index=0;
int temp1=0;
int temp2=0;
while(temp1<nums1.length&&temp2<nums2.length){
if(nums1[temp1]==nums2[temp2]){
tem[index]=nums1[temp1];
index++;
temp1++;
temp2++;
}else if(nums1[temp1]>nums2[temp2]){
temp2++;
}else{
temp1++;
}
}
int[] result=new int[index];
for(int i=0;i<index;i++){
result[i]=tem[i];
}
return result;
}
}
结果:
看了题解后发现最后的循环可以由Arrays.copyOfArray()来替代。
思考:如果数组原本有序,则选择第二种。如果nums2过大存储在硬盘上,那么就选择第一种。