[350. Intersection of Two Arrays II] C++ solution using sort + two pointers


  • 0
    class Solution {
    public:
        vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
            int i = 0;
            int j = 0;
            sort(nums1.begin(), nums1.end());
            sort(nums2.begin(), nums2.end());
            vector<int> result;
            
            while(i < nums1.size() && j < nums2.size())
            { 
                // if number in the list 1 is smaller than number in the list 2,
                // then increment list 1 index
                if(nums1[i] < nums2[j])
                {
                    i++;
                }
                // vice versa
                else if(nums1[i] > nums2[j])
                {
                    j++;
                }
                // if the values in the current indecies are the same,
                // then add to the result list
                else
                {
                    result.push_back(nums1[i]);
                    i++;
                    j++;
                }
            }
            
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.