【Leetcode 01】两数之和

leetcode刷题记录01

题目01 两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

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

分析及解法

解法1

首先,可以采用暴力解法,两层循环。先找到num2是否在列表中(需要判断是否重复利用了列表中的元素)
。如果可以找到,则返回num1 mum2的索引,如果无法找到,则继续循环。
代码如下:

class Solution:
    def twoSum(self,nums, target):
        for i in nums:
            j = target - i
            start_index = nums.index(i)
            next_index = start_index + 1
            temp_nums = nums[next_index: ]
            if j in temp_nums:
                return (nums.index(i),next_index + temp_nums.index(j))

解法二

解法二可以使用字典,效率要比第一种高出特别多,只需要使用一层循环。

class Solution:
    def twoSum(self,nums, target):
        dict = {}
        for i in range(len(nums)):
            if target - nums[i] not in dict:
                dict[nums[i]] = i
            else:
                return [dict[target-nums[i]],i]
posted @ 2019-11-21 15:27  zjkstudy  阅读(104)  评论(0编辑  收藏  举报