初级算法-6.两个数组的交集 II

题目描述:

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

示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]

示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]

分析:先对两个数组进行排序,然后按顺序查找

 1 class Solution {
 2     public int[] intersect(int[] nums1, int[] nums2) {
 3         Arrays.sort(nums1);
 4         Arrays.sort(nums2);
 5         int[] t=null;
 6         if(nums1.length<=nums2.length){
 7              t=new int[nums1.length];
 8         }
 9         else
10             t=new int[nums2.length];
11         int i=0,j=0,index=0;
12         while(i<nums1.length&&j<nums2.length){
13             if(nums1[i]<nums2[j])
14                 i++;
15             else{
16                 if(nums1[i]>nums2[j])
17                     j++;
18                 else{
19                     t[index++]=nums1[i];
20                     i++;j++;
21                 }
22             }
23         }
24         return Arrays.copyOf(t,index);
25     }
26 }
原文地址:https://www.cnblogs.com/hzhqiang/p/10759318.html