Leetcode刷题111-350. 两个数组的交集Ⅱ(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/submissions/]

350. Intersection of Two Arrays II

  • 1.Question
  • 2.Answer
  • 3.大神解答
  • 4.我的收获

1.Question

Given two arrays, write a function to compute their intersection.
Note:

1. Each element in the result should appear as many times as it shows in both arrays.
2. The result can be in any order.

Example 1 :

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2 :

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Follow up:

1. What if the given array is already sorted? How would you optimize your algorithm?
2. What if nums1's size is small compared to nums2's size? Which algorithm is better?
3. What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

2.Answer

medium类型题目。。

我的方法1:(暴力解法)
AC代码如下:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> res;
        for(int i = 0; i < nums1.size(); ++i)
        {
            for(int j = 0; j < nums2.size(); ++j)
            {
                if(nums1[i] == nums2[j])
                {
                    res.push_back(nums1[i]);
                    nums2.erase(nums2.begin() + j);
                    break;
                }
            }
        }
        return res;
    }
};

我的方法2:(明天补充)
AC代码如下:


3.大神解答

速度排名第一(快慢指针)。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next) {
            return false;
        }
        ListNode *slow = head;
        ListNode *fast = head->next->next;
        while (slow && fast) {
            if (fast == slow) {
                return true;
            }
            slow = slow->next;
            if (fast->next) {
                fast = fast->next->next;
            } else {
                fast = fast->next;
            }
        }
        return false;
    }
};

4.我的收获

排序。
fighting。。。

2019/7/1 胡云层 于南京 111

你可能感兴趣的:(LeetCode从零开始,LeetCode,C++)