Leetcode Daily Question: Intersection of Two Arrays

foreword

Speaking of algorithms, for the front end, it seems to be quite far away from our work, at least for me at present, it seems to be of little use. I have brushed Leetcode intermittently for more than half a year. I have read one or two hundred questions, but I feel that it is useless. When I encounter repeated questions, I don’t look at the solution. , I can rarely think of the optimal solution above the problem solution. The current attitude is to buy first-hand insurance, in case an interview happens to encounter a question that I have brushed and still remember.

topic description

Given two arrays nums1 and nums2, return their intersection. Each element in the output must be unique. We can ignore the order of the output results.

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]
Explanation: [4,9] is also passable

hint:

1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

simple solution

The first reaction is to loop through an array, determine whether each element is in another array, and finally deduplicate the array. So with the following code.

var intersection = function(nums1, nums2) {
   const result = []
   for(let i = 0;i<nums1.length;i++){
       if(nums2.includes(nums1[i])){
           result.push(nums1[i])
       }
   }
   return [...new Set(result)]
};

In the end, the prototype result looks pretty good, and the space complexity is n^2, but this question is classified in hash, obviously I don't want you to use the array method to solve it.

insert image description here

hash solution

includesChanging the method in the loop hashto judge by method can reduce the space complexity by n.

var intersection = function(nums1, nums2) {
  let set = new Set(nums1)
    let res = []
    for(let i = 0;i<nums2.length;i++){
        if(set.has(nums2[i])){
            res.push(nums2[i])
        }
    }
    return [...new Set(res)]
};

Judging from the running results, the time is only optimized by 20ms. This is because the problem has a limitation that the length of the array is less than 1000, and the amount of data is relatively small, so it seems that the time is about the same. If the amount of data is too large, it may even cause the operation to time out.
insert image description here

at last

I set the alarm clock early in the morning and got up to watch the game. The most angry thing was that I was crushed, and I didn’t even see the fifth round. Sure enough, it’s unreliable to put hope on JDG. Seeing the state, Teacher Dafei wants to win the first round Four crowns.

Guess you like

Origin blog.csdn.net/Salange1/article/details/127595234