Leetcode——Sort算法题
Easy
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
正确版本
:
import java.util.ArrayList;
import java.util.HashMap;
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i = 0; i < nums1.length; i++) //采用了HashMap结构来计数
{
if(map.containsKey(nums1[i])) map.put(nums1[i], map.get(nums1[i])+1);//若map中已存在则加一
else map.put(nums1[i], 1); //否则新添加该值
}
for(int i = 0; i < nums2.length; i++)
{
if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0)//若map中已存在nums2[i],且对应的次数>0
{
result.add(nums2[i]); //将这个共有的值添加到ArrayList集合中
map.put(nums2[i], map.get(nums2[i])-1); //将map中nums[i]对应的次数-1
}
}
//下面是将集合的元素转入到数组的办法
int[] r = new int[result.size()];
for(int i = 0; i < result.size(); i++)
{
r[i] = result.get(i);
}
return r;
}
}
当然,这边的
for(int i = 0; i < nums2.length; i++){
if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0)
{
result.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i])-1);
}
}
可以替换成:
for(int i:nums2){
if(map.containsKey(i)&&map.get(i)>0){
arr.add(i);
map.