zoukankan      html  css  js  c++  java
  • 初级算法-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 }
  • 相关阅读:
    电源
    SM2947
    网表
    cadence设计思路
    青山依旧在,几度夕阳红
    乐观锁与悲观锁
    笔记
    强弱软虚引用
    缓存相关
    dubbo
  • 原文地址:https://www.cnblogs.com/hzhqiang/p/10759318.html
Copyright © 2011-2022 走看看