计算两个数组的交
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2, 2]
.
挑战
- 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?
解题思路:
我们换一种数据结构,用HashMap<int,int>存储,遍历数组1中所有元素的时,key为数组元素,value为该数组元素出现的次数。遍历数组2中元素时,如果HashMap中元素的value值大于0,则value--,并将该元素放入结果数组中,否则continue。最后返回结果数组。
public class Solution {
/**
* @param nums1: an integer array
* @param nums2: an integer array
* @return: an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// write your code here
Map<Integer, Integer> map = new HashMap<>();
for(int i : nums1){
if(map.get(i) == null)
map.put(i, 1);
else
map.put(i, map.get(i)+1);
}
List<Integer> list = new ArrayList<>();
for(int i : nums2){
if(map.get(i) != null && map.get(i) > 0){
list.add(i);
map.put(i, map.get(i)-1);
}
}
int[] res = new int[list.size()];
for(int i=0; i<res.length; i++)
res[i] = list.get(i);
return res;
}
}
挑战:
如果数组全为有序数组,则可以采用双指针法,设置p1与p2分别遍历指向nums1和nums2,当*p1==*p2则保存进结果数组,否则让小的指针++,直到有一方数组遍历完毕结束,代码就不放了。