This is the 12th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
preface
Each JS algorithm problem a more, today is still a simple difficulty of the array related algorithm problem, the intersection of two arrays, the intersection here is the meaning of the same element, we look at the topic below
Topic describes
Given two arrays, write a function to calculate their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9, 4]
Their thinking
- Find the same item in both arrays, and the value cannot be repeated
- If the number exists in the other array, it will be put into the result array until the end of the loop
- Another approach is to first put two sort an array, and then declare two Pointers, points to two arrays, respectively, due to the array is sorted, only three kinds of circumstances, is a pointer to a number greater than 2 to the Numbers, then the pointer two mobile line, is a pointer to a pointer to less than two Numbers, the pointer to a mobile is ok at this moment, If two Pointers point to equal numbers, push into the result array
- The main point here is that if you use the second method, make sure to check whether the current item is the same as the previous item before moving, and if so, move the pointer back again until it is in a different position from the previous item
- Basically, these are the two ideas. Here’s the code for the first idea
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}* /
var intersection = function(nums1, nums2) {
const a = nums1.length
const b = nums2.length
let result = []
// There are two cases. The reason for this is that we only need to loop through the short array
if(a<b){
for(let i=0; i<a; i++){if(nums2.indexOf(nums1[i])! = = -1){
result.push(nums1[i])
}
}
}else{
for(let i=0; i<b; i++){if(nums1.indexOf(nums2[i])! = = -1){
result.push(nums2[i])
}
}
}
return Array.from(new Set(result)) // We use the Set() attribute to remove duplicates from the array
};
Copy the code
conclusion
This problem seems very simple, but still there are many kinds of problem solving method of them, here I only said two I first thought, and it is only to give the first idea of code, the second code is not posted here, at ordinary times array problems we stay two aspects, one is a pointer, one is the sorting, General array problems can be solved in both directions, gogogo!!