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

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

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

Example:

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

 

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

 to see which companies asked this question

1 public class Solution { 2     public int[] intersect(int[] nums1, int[] nums2) { 3         Set
set = new HashSet
(); 4 Arrays.sort(nums1); 5 Arrays.sort(nums2); 6 for(int i = 0,j = 0; i < nums1.length && j < nums2.length;){ 7 if(nums1[i] == nums2[j]){ 8 set.add(i++); 9 j++;10 }else if(nums1[i] < nums2[j]) i++;11 else j++;12 }13 14 int[] ans = new int[set.size()];15 int k = 0;16 for(Integer n : set){17 ans[k++] = nums1[n];18 }19 return ans;20 }21 }

使用hashset 记录重复出现元素的下标。

转载于:https://www.cnblogs.com/guoguolan/p/5653912.html

你可能感兴趣的文章
常见的软件架构
查看>>
基于Jmeter的轻量级接口压力测试(一)
查看>>
php解析xml文件的方法
查看>>
JS跨域请求
查看>>
Python正则表达式re
查看>>
svn安装配置使用小总结
查看>>
My SQL
查看>>
备份工具: bacula安装详解【转】
查看>>
第四章:为妹子镶上璀璨的珠宝
查看>>
Hexo搭建博客教程(1) - 安装环境与本地搭建
查看>>
[SDOI2015] 约数个数和 (莫比乌斯反演)
查看>>
[LeetCode] 406. Queue Reconstruction by Height Java
查看>>
winform 类似QQ的弹出消息窗口
查看>>
更换网站皮肤就这么简单
查看>>
Codeforces 12D Ball(线段树)
查看>>
C#中 父类与子类相互强制转换之实验
查看>>
统计iOS项目的总代码行数的方法
查看>>
三星S7短信不能提示的处理方法
查看>>
2、IValueConverter应用
查看>>
Emacs学习笔记(1):初学者的学习计划
查看>>