博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode| Intersection of Two Arrays
阅读量:4502 次
发布时间:2019-06-08

本文共 1307 字,大约阅读时间需要 4 分钟。

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;
}

转载于:https://www.cnblogs.com/wujunjie/p/5674391.html

你可能感兴趣的文章
css3的3D和2D
查看>>
简单的响应式布局的实现
查看>>
jQuery(属性操作)
查看>>
Python之路【第九篇】:Python面向对象
查看>>
background和background-image一点小区别
查看>>
ASCII码对照表
查看>>
HackerRank "Training the army" - Max Flow
查看>>
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected &#39;;&#39; at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>
python基础教程_学习笔记10:异常
查看>>
MATLAB——scatter的简单应用
查看>>
linux下复制粘贴快捷键
查看>>
什么是对象
查看>>
记录开发小程序
查看>>
WinSock服务程序
查看>>
巴西柔术第五课:过腿
查看>>