leetcode1——两数之和

题目:

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法一:首先最容易想到的就是暴力解法:

时间复杂度O(n^2)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(len(nums)):
            for j in range(len(nums)):
                if (nums[i] + nums[j] == target):
                    return [i, j]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Lp3Qfyxl-1583055145539)(day1_%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.assets/1583051587446.png)]

解法二:想到了指针的首尾查找,一个头指针和一个尾指针分别指向数组的首尾位置,两数之和大于target,尾指针前移,两数之和小于target,头指针后移,直到等于target,这种方法数组首先需要排序

问题:排序后的数组的下标就不一样了,一开始想到的是使用字典保存原始数组的下标和值,查找到之后就返回原数组的下标,然后发现字典的key不允许重复,如果数组中有重复值,比如nums = [2, 2, 1],保存到字典中之后只剩下一个值了,该方法不可取。

解决:只排序原数组的下标,使用 sorted_id 解决

时间复杂度:O(nlogn)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        sorted_id = sorted(range(len(nums)), key=lambda x:nums[x])
        # print(sorted_id)
        i = 0
        j = len(nums) - 1
        num_result = nums[sorted_id[i]] + nums[sorted_id[j]]
        while num_result != target:
            if (num_result < target):
                i += 1
            elif (num_result > target):
                j -= 1
            num_result = nums[sorted_id[i]] + nums[sorted_id[j]]
        return [sorted_id[i], sorted_id[j]]

解法三:直接用字典做,another_value = target - value

时间复杂度O(n)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict1 = {}
        for i, value in enumerate(nums):
            another_value = target - value
            if another_value in dict1:
                return [dict1[another_value], i]
            dict1[value] = i

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BIgpVlRX-1583055145542)(day1_%E4%B8%A4%E6%95%B0%E4%B9%8B%E5%92%8C.assets/1583054881195.png)]

ps:就算是简单的题也有值得思考学习的解法~继续加油!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值