leetcode 349. Intersection of Two Arrays

257 篇文章 17 订阅

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.
问题是要求两个数组的交集。

我的想法就是map,为什么需要两个map呢?第一个map很好理解,存入nums中出现的数字,而map2则用来记录结果数组中出现的数字,确保结果数组中的数字是独一无二的。

package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Intersection_of_Two_Arrays_349 {

	public int[] intersection(int[] nums1, int[] nums2) {
		if(nums1.length==0||nums2.length==0){
			return new int[]{};
		}
		int size=0;
		ArrayList<Integer> result=new ArrayList<Integer>();
		HashMap<Integer, Integer> map1=new HashMap<Integer, Integer>();
		HashMap<Integer, Integer> map2=new HashMap<Integer, Integer>();//map2的存在是防止result中的值不唯一
		for(int i=0;i<nums1.length;i++){
			if(map1.get(nums1[i])==null){
				map1.put(nums1[i], 0);//map的value随便取值
			}
		}
		for(int i=0;i<nums2.length;i++){
			if(map2.get(nums2[i])!=null){
				continue;
			}
			if(map1.get(nums2[i])!=null){
				size++;
				result.add(nums2[i]);
				map2.put(nums2[i], 0);
			}
		}
		int[] theResult=new int[size];
		for(int i=0;i<size;i++){
			theResult[i]=result.get(i);
		}
		return theResult;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Intersection_of_Two_Arrays_349 i=new Intersection_of_Two_Arrays_349();
		int[] nums1=new int[]{1,2,2,1};
		int[] nums2=new int[]{2,2};
		System.out.println(Arrays.toString(i.intersection(nums1, nums2)));
	}

}

大神思路跟我差不多,不过用的是hashset,时间复杂度也是O(m+n).

        HashSet<Integer> set = new HashSet<Integer>();
        ArrayList<Integer> res = new ArrayList<Integer>();
        //Add all elements to set from array 1
        for(int i =0; i< nums1.length; i++) set.add(nums1[i]);
        for(int j = 0; j < nums2.length; j++) {
           // If present in array 2 then add to res and remove from set 
           if(set.contains(nums2[j])) {
                res.add(nums2[j]);
                set.remove(nums2[j]);
            }
        }
        // Convert ArrayList to array
        int[] arr = new int[res.size()];
        for (int i= 0; i < res.size(); i++) arr[i] = res.get(i);
        return arr;
所以hashset和hashmap的区别到底是什么呢?可以看我下一篇文章 http://blog.csdn.net/huanghanqian/article/details/73920394
还有时间复杂度不如我俩解法的其他解法,放在下面看一看,拓宽一下思路。

Sort both arrays, use two pointers
Time complexity: O(nlogn)

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        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(nums1[i]);
                i++;
                j++;
            }
        }
        int[] result = new int[set.size()];
        int k = 0;
        for (Integer num : set) {
            result[k++] = num;
        }
        return result;
    }
}
Binary search
Time complexity: O(nlogn)
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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值