350. Intersection of Two Arrays II

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.
    Follow up:
  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

一刷
题解:这题很容易犯的错误是,如果有[2,2]和[2], 如果随机选一个作为binarysearch的参照,结果集会是[2,2]而不是正确的[2]。
这回采用的方法是,同时sort num1, num2,

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int len1 = nums1.length, len2 = nums2.length;
        int i=0, j = 0;
        List<Integer> res = new ArrayList<>();
        while(i<len1 && j<len2){
            if(nums1[i]<nums2[j]) i++;
            else if(nums1[i]>nums2[j]) j++;
            else{
                res.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] a = new int[res.size()];
        for(i=0; i<res.size(); i++) a[i] = res.get(i);
        return a;   
    }
}

二刷:
思路同一刷

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> res = new ArrayList<Integer>();
        int i = 0, j = 0;
        int len1 = nums1.length, len2 = nums2.length;
        while(i<len1 && j<len2){
            if(nums1[i] <nums2[j]) i++;
            else if(nums1[i] > nums2[j]) j++;
            else{
                res.add(nums1[i]);
                i++;
                j++;
            }
        }
        int[] a = new int[res.size()];
        for(int in=0; in<res.size(); in++){
            a[in] = res.get(in);
        }
        return a;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容