leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0349.cpp (1055B)


      1 
      2 class Solution {
      3   public:
      4     vector<int> intersection(vector<int> &nums1, vector<int> &nums2) const {
      5         const int n = size(nums1), m = size(nums2);
      6         int i = 0, j = 0;
      7         vector<int> res;
      8 
      9         sort(begin(nums1), end(nums1));
     10         sort(begin(nums2), end(nums2));
     11         while (i < n && j < m) {
     12             if (nums1[i] == nums2[j]) {
     13                 const int crnt = nums1[i];
     14                 res.push_back(crnt);
     15                 while (i < n && nums1[i] == crnt)
     16                     i++;
     17                 while (j < m && nums2[j] == crnt)
     18                     j++;
     19             } else if (nums1[i] > nums2[j])
     20                 j++;
     21             else
     22                 i++;
     23         }
     24         return res;
     25     }
     26 };
     27 
     28 class Solution {
     29   public:
     30     vector<int> intersection(const vector<int> &nums1, const vector<int> &nums2) const {
     31         unordered_set<int> st(begin(nums1), end(nums1));
     32         vector<int> res;
     33         for (const int n : nums2) {
     34             if (st.erase(n)) res.push_back(n);
     35         }
     36         return res;
     37     }
     38 };