zoukankan      html  css  js  c++  java
  • Lc349_Intersection

     1import java.util.HashSet;
    2import java.util.Set;
    3
    4/**
    5 * 349. 两个数组的交集
    6 * 给定两个数组,编写一个函数来计算它们的交集。
    7 * <p>
    8 * <p>
    9 * <p>
    10 * 示例 1:
    11 * <p>
    12 * 输入:nums1 = [1,2,2,1], nums2 = [2,2]
    13 * 输出:[2]
    14 * 示例 2:
    15 * <p>
    16 * 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    17 * 输出:[9,4]
    18 * <p>
    19 * <p>
    20 * 说明:
    21 * <p>
    22 * 输出结果中的每个元素一定是唯一的。
    23 * 我们可以不考虑输出结果的顺序。
    24 */

    25public class Intersection {
    26    /**
    27     * 通过hash表实现,因为没有限制大小 所以用集合
    28     *
    29     * @param nums1
    30     * @param nums2
    31     * @return
    32     */

    33    public static int[] intersection(int[] nums1, int[] nums2) {
    34        Set<Integer> set = new HashSet<>();
    35        Set<Integer> res = new HashSet<>();
    36
    37
    38        for (int i = 0; i < nums1.length; i++) {
    39            set.add(nums1[i]);
    40        }
    41        for (int i = 0; i < nums2.length; i++) {
    42            if (set.contains(nums2[i])) {
    43                res.add(nums2[i]);
    44            }
    45        }
    46
    47
    48        int resArray[] = new int[res.size()];
    49        int j = 0;
    50        for (Integer r : res) {
    51            resArray[j++] = r.intValue();
    52        }
    53
    54        return resArray;
    55    }
    56
    57    public static void main(String[] args) {
    58        int [] nums1 = {4,9,5}, nums2 = {9,4,9,8,4};
    59        intersection(nums1,nums2);
    60    }
    61}
    不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!
  • 相关阅读:
    字符转int 的几种方法
    递归在类中的写法
    修改多维才智的名字
    max中用 .net 判断输入的邮箱地址是否合格。
    找处场景中同名称的结点
    Android Button [ 学习笔记 一 ] 原创
    Android中Listview注意事项
    Android 移动开发一本就够学习笔记一
    ListActivity 学习[原创]
    在 Eclipse 中导入 Android 示例程序
  • 原文地址:https://www.cnblogs.com/xiaoshahai/p/14378265.html
Copyright © 2011-2022 走看看