[LeetCode-349] Intersection of Two Arrays(java)

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.
题意:
现有两个数组,计算两个数组中的重复值并返回。返回的结果中,重复值必须唯一,但可以是任意顺序(即可以打乱顺序)。
分析:
这里采用一种比较好理解的方法。先将两个数组分别按大小排序,然后再循环比较数组元素是否相等;如果相等,需要考察暂存数组temp(显然temp中元素会是有序的),如果temp为空或者最后一个元素不等于当前元素,就将当前元素加入temp中;如果不等,就要把小的元素的指针后移。

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        //nums1和nums2数组的长度
        int len1=nums1.length;
        int len2=nums2.length;
        //暂存nums1和nums2中相同的数,最后数组尾部会有多余的0
        int[] temp=new int[len1];
        //记录temp数组下标
        int index=0;
        //现将nums1和nums2数组都排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i=0,j=0;
        while(i<len1&&j<len2){
            //循环比较按大小排序后的数组,如果相等
                if(nums1[i]==nums2[j])
                {
                 //并且temp数组中没有值或者数组中最大的值不等于当前比较的值,则插入temp中
                    if(index==0||temp[index-1]!=nums1[i])
                    {
                        temp[index]=nums1[i];
                        index++;
                    }
                    i++;
                    j++;
                }
                //如果不相等,增大当前较小值所在数组的索引
                else if(nums1[i]<nums2[j]){
                    i++;
                }
                else{
                    j++;
                }
            }
            //保存最终的结果
            int[] result=new int[index];
    //因为上面的暂存数组temp,末尾会有多余的0,故重新根据intersection个数,赋值到result数组
            for(int k=0;k<index;k++){
                result[k]=temp[k];
            }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值