Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
利用数组的indexof
var intersection = function(nums1, nums2) {
var num1 = nums1.length;
var num2 = nums2.length;
return num1 < num2 ? compare(nums1,nums2,num1) : compare(nums2,nums1,num2);
function compare(a,b,num) {
var result = [];
for (var i = 0;i<num;i++){
if (result.indexOf(a[i])===-1) {
if (b.indexOf(a[i])!==-1) {
result.push(a[i]);
}
}
}
return result;
}
};
网友评论