350. Intersection of Two Arrays
2016-10-10 本文已影响0人
AlanGuo
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?
Solution:
Two-pointer walk.
感觉代码有些地方写得太啰嗦了,有空优化一下:
public class Solution {
public int[] intersect(int[] nums1, int[] nums2)
{
List<Integer> result = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0;
while(i < nums1.length && j < nums2.length)
{
while(nums1[i] < nums2[j])
{
i++;
if(i == nums1.length) break;
}
if(i >= nums1.length || j >= nums2.length) break;
while(nums1[i] > nums2[j])
{
j++;
if(j == nums2.length) break;
}
if(i >= nums1.length || j >= nums2.length) break;
if(nums1[i] == nums2[j])
{
result.add(nums1[i]);
i++; j++;
}
}
int size = result.size();
int[] resultArray = new int[size];
for(int cao = 0; cao < size; cao++)
{
resultArray[cao] = result.get(cao);
}
return resultArray;
}
}
看了 tag,除了 two-pointer walk 之外,还可以用 HashTable(HashMap)……厉害了我的 Map!
尝试一下:
public class Solution
{
public int[] intersect(int[] nums1, int[] nums2)
{
List<Integer> result = new ArrayList<>();
HashMap<Integer, Integer> hm = new HashMap<>();
for(int a : nums1)
{
int newCount = hm.getOrDefault(a, 0);
newCount++;
hm.put(a, newCount);
}
for(int b : nums2)
{
int newCount = hm.getOrDefault(b, 0);
newCount--;
if(newCount >= 0)
result.add(b);
hm.put(b, newCount);
}
int[] resultArray = new int[result.size()];
for(int i = 0; i < result.size(); i++)
{
resultArray[i] = result.get(i);
}
return resultArray;
}
}
HashMap (HashTable) 爸爸好!