zoukankan      html  css  js  c++  java
  • leetcode 349 两个数组的交集

    // 方法1
    public static int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0
            || nums2 == null || nums2.length == 0) {
            return new int[]{};
        }
    
        List<Integer> integerNum1 = new ArrayList<>();
        Map<Integer, Integer> integers = new HashMap<>();
        for (int num : nums1) {
            if (!integerNum1.contains(num))
                integerNum1.add(num);
        }
        for (int num : nums2) {
            if (integerNum1.contains(num)) {
                integers.put(num, 1);
            }
        }
        int[] res = new int[integers.size()];
        int index = 0;
        for (Map.Entry entry : integers.entrySet()) {
            res[index++] = (int)entry.getKey();
        }
        return res;
     }
    
    // 方法2
    public static int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0
            || nums2 == null || nums2.length == 0) {
            return new int[]{};
        }
    
        Set<Integer> integerSet = new HashSet<>();
        for (int num : nums1) {
            integerSet.add(num);
        }
        int[] res = new int[nums2.length];
        int index = 0;
        for (int num : nums2) {
            if (integerSet.contains(num)) {
                res[index++] = num;
                integerSet.remove(num);
            }
        }
        return Arrays.copyOf(res, index);
    }
    
    // 测试用例
    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 2, 1}, nums2 = new int[]{2, 2};
        int[] ans = intersection(nums1, nums2);
        System.out.println("Intersection demo01 result:");
        for (int res : ans) {
            System.out.print(res + " ");
        }
        System.out.println();
        nums1 = new int[]{4, 9, 5};
        nums2 = new int[]{9, 4, 9, 8, 4};
        ans = intersection(nums1, nums2);
        System.out.println("Intersection demo02 result:");
        for (int res : ans) {
            System.out.print(res + " ");
        }
        System.out.println();
    }
    

    leetcode 350: 两个数组的交集II
    https://www.cnblogs.com/fyusac/p/13292985.html

  • 相关阅读:
    字符串基本操作
    条件、循环、函数定义 练习
    turtle库基础练习
    Python基础练习
    AutoLayout 教程
    Mac上最佳的SVN管理工具:Cornerstone
    图片上传 关于压缩的问题
    关于单元测试的问题
    获取ios设备的当前IP地址
    关于项目使用ARC的管理方式
  • 原文地址:https://www.cnblogs.com/fyusac/p/13913356.html
Copyright © 2011-2022 走看看