Leetcode350. Intersection of Two Arrays II

来源:互联网 发布:sql server 导出数据库 编辑:程序博客网 时间:2024/06/16 16:33

一、原题

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

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

二、思路

与之前求两数组的重叠部分不同,这次要求交集可以有重复的元素。

首先将两个数组进行排序

然后遍历两个数组,使用变量i 和j 分别指向两个数组,遍历两个数组的元素是否相同。如果相同,则放在集合中;如果前者小,则i后移;若后者小,则j后移

要点:将数组排序,list集合和数组转换,

三、代码

public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        //首先将num1、num2排序
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer>list=new ArrayList<>();
for(int i=0,j=0;i<nums1.length&&j<nums2.length;){
if(nums1[i]==nums2[j]){
list.add(nums1[i]);
i++;
j++;
}
else if (nums1[i]<nums2[j]) {
i++;
}
else {
j++;
}
}
//将list集合中的数据转化为数组
int[]nums=new int[list.size()];
for (int k = 0; k < list.size(); k++) {
nums[k]=list.get(k);
}
return nums;
    }
}
0 0
原创粉丝点击