LeetCode 350. Intersection of Two Arrays II

博客围绕计算两个数组交集展开,给出了具体题目和示例。介绍了先排序再操作的计算方法,将相同元素加入ArrayList后转成int[]。还提出扩展问题,如数组已排序、两数组大小差异、磁盘存储且内存有限时如何优化算法等。

题目:

给定两个数组,写一个函数来计算它们的交集。

 

注意: 

结果中的每个元素的出现次数应该与它在两个数组中显示的次数相同。

结果可以是任意顺序的。

Given two arrays, write a function to compute their intersection.

Input: nums1 = [1,2,2,1], nums2 = [2,2]       Output: [2,2]

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]

Note:

     Each element in the result should appear as many times as it shows in both arrays.

     The result can be in any order.

 

方法:

先对数组进行排序,对排好序的数组进行操作

如果相同,则同时往后挪一位;如果不同,则将更小的数往后挪一位;

相同的数加入到ArrayList中,最后转成int[]

 

代码:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> interList = new ArrayList<Integer>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int i = 0,j = 0;
        while(i<nums1.length&&j<nums2.length){
            if(nums1[i] == nums2[j]){
                interList.add(nums1[i]);
                i++;
                j++;
            }else if(nums1[i]>nums2[j]){
                j++;
            }else{
                i++;
            }
        }
        
        int[] interArray = new int[interList.size()];
        Iterator it = interList.iterator();
        i=0;
        while(it.hasNext()){
            interArray[i]=(Integer)(it.next());
            i++;
        }
        
        return interArray;
    }
}

 

扩展问题:

如果给定的数组已经排序了怎么办?如何优化算法?

如果nums1的大小比nums2的小怎么办?哪种算法更好?

如果nums2的元素存储在磁盘上,并且内存有限,以至于不能一次将所有元素加载到内存中,该怎么办?

——可以将nums1的元素存在hashmap中,结构为数-次数,再依次对nums2中的元素进行判断,存在则加入到reList中并且对次数减1

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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值