Python and C++ codes sorting and comparing


  • 0
    W
    class Solution(object):
        def intersection(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            n,m=len(nums1),len(nums2)
            if n==0 or m==0:
                return []
            nums1.sort()
            nums2.sort()
            re=[float('Inf')]
            i,j=0,0
            while i<n and j<m:
                if nums1[i]==nums2[j]:
                    if nums1[i] !=re[-1]:
                        re.append(nums1[i])
                    i+=1
                    j+=1
                elif nums1[i]<nums2[j]:
                    i+=1
                elif nums1[i]>nums2[j]:
                    j+=1
            re.pop(0)
            return re
    

    C++ 8 ms 87%

    class Solution {
    public:
        vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
            int n=nums1.size(); int m=nums2.size();
            vector<int> re;
            if(n==0||m==0) {return re;}
            sort(nums1.begin(), nums1.end());
            sort(nums2.begin(), nums2.end());
            int i=0; int j=0;
            while(i<n&&j<m){
                if (nums1[i]==nums2[j]){
                    if(re.empty()||nums1[i]!=re[re.size()-1])
                    re.push_back(nums1[i]);
                    i++;j++;}
                else if(nums1[i]<nums2[j])i++;
                else j++;
            }return re;
        }
    };

Log in to reply
 

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