LeetCode刷题记录-两数之和——超过99.61%的提交

刷题链接:力扣-两数之和
题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

我的解法:
先排序,再双指针法,当首尾两数之和大于target时,右指针左移,反之左指针右移。

import copy

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        temp = copy.copy(nums)
        temp.sort()
        while True:
            if len(temp)==1:
                break
            if (temp[0] + temp[-1]) == target:
                num1 = nums.index(temp[0])
                num2 = nums.index(temp[-1])
                if num1 == num2:
                    nums.pop(num1)
                    num2 = nums.index(temp[-1])+1
                return [num1, num2]
            elif (temp[0] + temp[-1]) > target:
                temp.pop(-1)
                continue
            else:
                temp.pop(0)
                continue
        return [-1,-1]

提交结果:

执行用时:24ms 94.10% 内存消耗:12.6MB 99.23%

优化后的代码:减少删除操作

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        temp = sorted(nums)
        num1 = 0
        num2 = len(temp)-1
        while True:
            if temp[num1] == temp[num2]:
                break
            if (temp[num1] + temp[num2]) == target:
                return [nums.index(temp[num1]), nums.index(temp[num2])]
            elif (temp[num1] + temp[num2]) > target:
                num2 -= 1
                continue
            else:
                num1 += 1
                continue
        a = nums.index(temp[num1])
        nums[nums.index(temp[num1])] = temp[num1] - 1
        return [a, nums.index(temp[num1])]

提交结果:

执行用时: 12ms 99.61% 内存消耗:12.5MB 99.76%

时间复杂度:排序O(nlogn),遍历O(n)
别人的方法:
直接查找。

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        r_nums={}
        for index,num in enumerate(nums):
            jieguo = target - num
            if jieguo in r_nums:
                return [r_nums[jieguo],index]
            r_nums[num] = index
        return 0

有个思想,尽量不处理用不到的数据。
当在待查数组里没有找到差值时,就把自己加入待查数组。这样可以在最好情况下极大的减少时间消耗。Python内置方法的时间复杂度:查找 O(n),排序O(nlogn)。所以该方法的最差情况为O(n^2)。

Python内置方法的时间复杂度

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值