350. Intersection of Two Arrays II
Leetcode
題目
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.解答
var intersect = function(nums1, nums2) {
const hash = {};
for(let i=0; i<nums1.length; i++) {
const value = nums1[i];
if(!hash[value]) hash[value] = 1;
else hash[value]++;
}
const arr = [];
for(let i=0; i<nums2.length; i++) {
const value = nums2[i];
if(!hash[value]) continue;
else {
arr.push(value);
hash[value]--;
}
}
return arr;
};測資
Last updated