Leetcode刷题记录——1. 两数之和

在这里插入图片描述
我一共实现了两种方法:蛮力法+字典法
从这道题中,我觉得可以总结的是:
循环嵌套的问题可以通过查询的方式降低复杂度!

1、字典法(简介)

首先,我们记录nums中所有出现过的数字和它们第一次出现的具体位置到一个字典中
(key = 每个数字, value = 这个数字对应的index)。

现在 将nums中所有元素都减去target
这样,如果i位置上的数从n变为m,则m = n - target, target>0
考虑m和n都是正整数,则m肯定是负数。
那么,如果我们能在起初的字典中找到-m,则说明我们找到了符合题意的两个数字。
此时,返回它们的index即可,其中第一个数字的下标为i,第二个数字的下标为newdict[-m]

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        newdict = {}#这里用来盛放输入数组nums中每个数在nums中第一次出现的下标
        length = len(nums)
        for i,value in enumerate(nums):
            if value not in newdict:
                newdict[value] = i#记录下标记
        for i in range(length):
            nums[i] -= target
        for i,valuea in enumerate(nums):
            if (-1*valuea) in newdict and newdict[(-1*valuea)] != i:
                return [i,newdict[(-1*valuea)]]

2、蛮力法:
两个for循环
无借鉴意义

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        newlist = []
        change = False
        over = False
        newdict = {}
        founda = False
        foundb = False
        if len(nums)<=1:
            return newlist
        for i,value in enumerate(nums):
            newdict[i] = value
        nums = sorted(nums)
        for i in range(len(nums)-1):
            valuea = nums[i]
            for j in range(i+1,len(nums)):
                valueb = nums[j]
                tempsum = valuea + valueb
                if tempsum == target:
                    over = True
                    break
                elif tempsum > target:
                    change = True
                    break
            if change is True:
                change = False
                continue
            if over is True:
                break

        for i in range(len(nums)):
            if i < len(nums) and  newdict[i] == valuea and founda is False:
                newlist.append(i)
                del newdict[i]
                founda = True
                if len(newlist) == 2:
                    return newlist
                continue
            if i < len(nums) and newdict[i] == valueb and foundb is False:
                newlist.append(i)
                del newdict[i]
                foundb = True
                if len(newlist) == 2:
                    return newlist
                continue
发布了43 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41545780/article/details/104925078
今日推荐