您的位置:首页 > 其它

【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 = 
[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]+" ");
//}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: