两数组的交-LintCode

思路一: 先排序,然后依次遍历,时间复杂度是nlog(n),仅仅排序耗时:

python代码:

class Solution:
    def intersection(self, nums1, nums2):
        len1 = len(nums1)
        len2 = len(nums2)
        nums1.sort()
        nums2.sort()
        i = 0
        j = 0
        result = []
        while (i < len1) and (j < len2):
            if nums1[i] == nums2[j]:
                temp = nums1[i]
                result.append(nums1[i])
            while i+1 < len1 and nums1[i] == nums1[i+1]:
                i += 1
            while j+1 < len2 and nums2[j] == nums2[j+1]:
                j += 1
            if nums1[i] < nums2[j]:
                i += 1
            else:
                j += 1
        return result
C++代码:

class Solution {
public:
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        // Write your code here
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int len1 = nums1.size();
        int len2 = nums2.size();
        vector<int> A;
        int i = 0, j = 0;
        while (i < len1 && j < len2) {
            if(nums1[i] == nums2[j]){
                A.push_back(nums1[i]);
            }
            while (nums1[i] == nums1[i+1])
                i++;
            while (nums2[j] == nums2[j+1])
                j++;
            if (nums1[i] < nums2[j]){
                i++;
            }else{
                j++;
            }
        }
        return A;
    }
};

思路二:两数组求集合,然后再相交,

python代码:(看到语法糖的厉害了吧):

class Solution:  
    def intersection(self, nums1, nums2):  
        return list(set(s1) & set(s2))  
C++代码:

class Solution {
public:
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        // Write your code here
        set<int> temp1;
        set<int> temp2;
        for (auto i : nums1) {
            temp1.insert(i);
        }
        for (auto j : nums2) {
            temp2.insert(j);
        }
        vector<int> A;
        for (auto i : temp1) {
            if (temp2.find(i) != temp2.end()) {
                A.push_back(i);
            }
        }
        return A;
    }
};
但是上面的C++的代码是最耗时的。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值