zoukankan      html  css  js  c++  java
  • [leetcode]349. Intersection of Two Arrays数组交集

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

    Example 1:

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

    Example 2:

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

    题意:

    如题

    Solution1:  HashSet

    1.  Scan nums1,  put items in nums1 to set1

    2. Scan nums2, check each item is contained in set1 

         

       

    注意: HashSet.contains() -> O(1) 

    code

     1 class Solution {
     2   public int[] intersection(int[] nums1, int[] nums2) {
     3         HashSet <Integer> set1 = new HashSet<>(); 
     4         HashSet <Integer> resSet = new HashSet<>(); 
     5         
     6         for (int i = 0; i < nums1.length; i ++) {
     7             set1.add(nums1[i]);
     8         }
     9         for (int i = 0; i < nums2.length; i ++) {
    10             if (set1.contains(nums2[i])) {  
    11                 resSet.add(nums2[i]);
    12             }
    13         } 
    14         //  resSet -> int[]res
    15         int [] res = new int[resSet.size()];
    16         int index = 0;
    17         for (int num : resSet) {
    18             res[index++] = num;
    19         }
    20         return res;
    21     }
    22 }
  • 相关阅读:
    CSPS模拟 57
    CSPS模拟 56
    CSPS Oct目标
    CSPS模拟 55
    CSPS模拟 54
    CSPS模拟 53
    和manacher有关的乱写
    CSPS模拟 52
    CSPS模拟 51
    Git和代码规范
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9810411.html
Copyright © 2011-2022 走看看