leetcode之两数之和

思路:先排序,在遍历。排序用快速排序,时间复杂度为 O ( n l o g n ) O(nlogn) O(nlogn),遍历的时间复杂度为 O ( n ) O(n) O(n),总的时间复杂度为 O ( n l o g n ) O(nlogn) O(nlogn)
空间复杂度 O ( n ) O(n) O(n).
执行用时: 52 ms ,超过31%
内存消耗: 13.3 MB,超过42%

class Solution(object):
    def quick_sort(self, nums, l, r):
        if l<r:
            i = l
            j = r
            k = nums[i]
            while(i<j):
                # 从右往左
                # print(nums)
                while nums[j]>=k and i<j:
                    j -= 1
                if i<j:
                    nums[i] = nums[j]
                while nums[i]<=k and i<j:
                    i += 1
                if i<j:
                    nums[j] = nums[i]
            nums[i] = k
            self.quick_sort(nums, l ,i-1)
            self.quick_sort(nums, i+1 ,r)
            
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        import copy
        newnums = copy.deepcopy(nums)
        self.quick_sort(nums, 0, len(nums)-1)
        i = 0
        j = len(nums)-1
        while(i<j):
            if nums[i] + nums[j]>target:
                j -= 1
            if nums[i] + nums[j]<target:
                i += 1
            if nums[i] + nums[j]==target:
                if nums[i]== nums[j]:
                    return [newnums.index(nums[i]),newnums.index(nums[j],newnums.index(nums[i])+1)]
                else:
                    return [newnums.index(nums[i]),newnums.index(nums[j])]

别人的做法
这个思路和我是一样的,学python这么久了还没有用sorted这个函数,记录一下。
执行用时: 44 ms,超过54%
内存消耗: 14.9 MB,超过23%

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
            sort_id = sorted(range(len(nums)), key=lambda k: nums[k])
            head = 0
            tail = len(nums)-1
            result = nums[sort_id[head]] + nums[sort_id[tail]]
            while result != target:
                if result > target:
                    tail -= 1
                if result < target:
                    head += 1
                result = nums[sort_id[head]] + nums[sort_id[tail]]
            return [sort_id[head], sort_id[tail]]

暴力枚举法:拿出一个数字,用target减去它,如果得到的结果在这个数字往后的列表里,那就返回他们的索引值。
执行用时: 28 ms,超过100%
内存消耗: 15 MB,超过14%

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
            length = len(nums)
            for i in range(length):
                res = target - nums[i]
                if res in nums[i+1:]:
                    return [i, nums[i+1:].index(res)+i+1]

总结:如果最求速度的话能用内置函数就用内置函数,毕竟官方的代码效率是比绝大部分人都要高的。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值