您当前的位置: 首页 > 

宝哥大数据

暂无认证

  • 1浏览

    0关注

    1029博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

两数之和

宝哥大数据 发布时间:2019-09-27 10:27:28 ,浏览量:1

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

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

示例:

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

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

1、暴力破解, 超出时间限制范围
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)): 
            for j in range(i + 1, len(nums)):
                if target == nums[i] + nums[j] : 
                    return [i, j]
        
2、使用dict遍历

在这里插入图片描述

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dicts = {}
        
        for i in range(len(nums)): 
            dicts[nums[i]] = i
            
        for j in range(len(nums)):
            numJ = nums[j] 
            numI = target - numJ
            if numI in dicts:
                i = dicts[numI]
                if (i != j):
                    return [j, i]
            
3、一遍dict遍历 enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中

在这里插入图片描述

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        _dict = {}
        for i, m in enumerate(nums):
            if _dict.get(target - m) is not None:
                return [_dict.get(target - m), i]
            _dict[m] = i

二、两数之和 II - 输入有序数组

在这里插入图片描述

2.1、双指针

头尾两个指针,如果小了,头指针往后,如果大了,尾指针往前

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i, j = 0, len(nums)-1
        while i < j: 
            if nums[i] + nums[j] == target:
                return [i + 1, j + 1]
            elif nums[i] + nums[j] < target:
                i = i + 1
            else :
                j  = j - 1
        
        
关注
打赏
1587549273
查看更多评论
立即登录/注册

微信扫码登录

0.0454s