zoukankan      html  css  js  c++  java
  • 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]

    Note:

    • Each element in the result must be unique.
    • The result can be in any order.
    class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            HashSet<Integer> set1 = new HashSet<Integer>();
            for (Integer n : nums1) set1.add(n);
            HashSet<Integer> set2 = new HashSet<Integer>();
            for (Integer n : nums2) set2.add(n);
            
            int[] res = new int[Math.min(set1.size(), set2.size())];
            int ind = 0;
            for(Integer i: set1) if(set2.contains(i)) res[ind++] = i;
            return Arrays.copyOf(res, ind);
        }
    }

    要是我的话估计还要用一个hashmap,其实并不用,巧用数组以及Arrays.copyOf(orig array, length).

  • 相关阅读:
    ftell
    diff
    继承
    类的组合
    拷贝构造函数
    内存管理
    Hibernate学习-Hibernate查询语言HQL
    JAVA解析JSON数据
    Android异步加载
    Android数据存储-文件操作
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12258286.html
Copyright © 2011-2022 走看看