C++ Solution using sort. O(n log n + m log m)


  • 0
    class Solution {
     public:
       	vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
       		int n1 = nums1.size(), n2 = nums2.size();
    		vector<int> res;
    		if (n1 == 0 || n2 == 0) return res;
    		sort(nums1.begin(), nums1.end());
    		sort(nums2.begin(), nums2.end());
    		for (int i = 0, j = 0; i < n1 && j < n2; ) {
    			if (nums1[i] < nums2[j]) ++i;
    			else if (nums1[i] > nums2[j]) ++j;
    			else if (nums1[i] == nums2[j]) {
    				if (res.empty() || res.back() != nums1[i])
    					res.push_back(nums1[i]);
    				++i;
    				++j;
    			}
    		}
    		return res;
    	}
    };

Log in to reply
 

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