【Leetcode】350. Intersection of Two Arrays II(HashSet,Sort)
2016-06-04 01:27
453 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
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 num2'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?
关键字:HashSet,Sort
题意:给出两个int数组,返回重复出现的数字组成的数组,可重复,可扰乱顺序。
思路:先把两个数组排序,再用两个index下标指向两个数组,用hashset保存第一个数组nums1中被选中的数字的下标。再根据hashset保存的下标取出nums1的数字存到result数组,返回result数组。
两个数组的快排的时间复杂度为 O(n
log n + m log m) , n, m, 分别为两个数组的长度。
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 num2'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?
关键字:HashSet,Sort
题意:给出两个int数组,返回重复出现的数字组成的数组,可重复,可扰乱顺序。
思路:先把两个数组排序,再用两个index下标指向两个数组,用hashset保存第一个数组nums1中被选中的数字的下标。再根据hashset保存的下标取出nums1的数字存到result数组,返回result数组。
两个数组的快排的时间复杂度为 O(n
log n + m log m) , n, m, 分别为两个数组的长度。
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { HashSet<Integer> set = new HashSet<>(); int index1, index2; //int[] nums1 = new int[]{1, 2, 2, 1}; //int[] nums2 = new int[]{2, 2}; Arrays.sort(nums1); Arrays.sort(nums2); for(index1 = 0, index2 = 0; index1 < nums1.length && index2 < nums2.length; ) { if(nums1[index1] == nums2[index2]) { set.add(index1); index1++; index2++; } else if(nums1[index1] < nums2[index2]) { index1++; } else { index2++; } } int result[] = new int[set.size()]; int i = 0; for(Integer index : set) { result[i++] = nums1[index]; } return result; //for(int j = 0; j < i; j++) //{ //System.out.print(result[j]+" "); //} } }
相关文章推荐
- CUDA从入门到精通(二):第一个CUDA程序
- CUDA从入门到精通(一):环境搭建
- Android事件分发机制
- CUDA从入门到精通(零):写在前面
- GPU(CUDA)学习日记(十五) ------ CUDA 5 的一些介绍与下载
- ios之地理编码常用知识整理
- 利用KeyValuePair生成sql键值对csharpVS2015
- Basic Calculator
- 爬虫小程序(实习僧网抓取数据)
- Java程序员应该掌握
- GPU(CUDA)学习日记(十四)------CUDA软件更新信息 Parallel Nsight 3.0新特性以及NVAPI介绍
- oracle 11g expdp 备份解决空表无法备份
- js单击事件及超链接触发失败原因之一(经验分享)
- GPU(CUDA)学习日记(十三)------ CUDA内存简介
- math.h里的数学计算公式介绍
- ios 之MKAnnotationView与MKPinAnnotationView 的区别
- Linux crontab定时执行任务 命令格式与详细例子
- leetcode 73. Set Matrix Zeroes
- ubuntu-16.04 详细安装教程(图文)附下载地址
- 开始做个作品总结吧