• leetcode| Intersection of Two Arrays


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

    Example:
    Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

    Note:

      • Each element in the result must be unique.
      • The result can be in any order.

    题目:一目了然找出两个数组的交集

    思路:我的大概想法是,先将两个数组分别去重,而后合成一个数组,对该数组进行排序,而后数组中相邻两个元素相等的即为交集元素,即num[i] == num[i-1]

    代码有点冗余,效率一般,

    public int[] intersection(int[] nums1, int[] nums2) {

    int len1 = nums1.length, len2 = nums2.length, j = 0;
    if(len1 == 0 || len2 == 0){
    return new int[0];
    }
    HashSet<Integer> set1 = new HashSet<Integer>();
    HashSet<Integer> set2 = new HashSet<Integer>();
    HashSet<Integer> set3 = new HashSet<Integer>();
    for (int i = 0; i < len1; i++) {
    set1.add(nums1[i]);
    }
    for (int i = 0; i < len2; i++) {
    set2.add(nums2[i]);
    }
    int[] temp = new int[set1.size() + set2.size()];
    Iterator it1 = set1.iterator();
    while (it1.hasNext()) {
    temp[j++] = (Integer) it1.next();
    }
    Iterator it2 = set2.iterator();
    while (it2.hasNext()) {
    temp[j++] = (Integer) it2.next();
    }
      Arrays.sort(temp);

    for (int i = 1; i < temp.length; i++) {
      if (temp[i] == temp[i - 1] ) {
         set3.add(temp[i]);
        }
      }
      int res[] = new int[set3.size()];
      j = 0;
      Iterator it3 = set3.iterator();
      while (it3.hasNext()) {
        res[j++] = (Integer) it3.next();
      }
      return res;

    }

  • 相关阅读:
    Django——不同版本
    04爬取拉勾网Python岗位分析报告
    24 两两交换链表中的节点
    UniGUI学习之UniImage(39)
    Delphi7开发简单文件传输
    Javaday03(补充day02运算符,流程控制)
    java中代码块,构造方法和普通方法的代码执行顺序
    +=隐式类型转换
    关于switch中的default
    Java操作JSON数据(5)--jettison操作JSON数据
  • 原文地址:https://www.cnblogs.com/wujunjie/p/5674391.html
Copyright © 2020-2023  润新知