LeetCode 两个数之和

英文:Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

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

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

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
#解法一:求差值,判断差值是否在nums数组里
class Solution:
    def twoSum(self,nums,target):
        n = len(nums)
        for x in range(n):
            b = target - nums[x]
            if b in nums:
                y = nums.index(b)
                if y != x:
                    return [x,y]

nums = [2,7,11,13]
target = 9
res = Solution().twoSum(nums,target)
print(res)
#解法二:求差值、把差值存进字典里作为键、索引作为值,第一次循环理解:d[7]=0 即字典d={7:0},表示为索引0需要数组里值为7的元素配对。 if 判断是否为前面元素所需要配对的值 , 是则返回两个索引值。(补充:nums[x] in d  是判断值是否在字典某个key里面)
class Solution:
    def twoSum(self,nums,target):
        n = len(nums)
        d ={}
        for x in range(n):
            a = target - nums[x]
            if nums[x] in d:
                return d[nums[x]],x
            else:
                d[a] = x

nums = [2,7,11,13]
target = 9
res = Solution().twoSum(nums,target)
print(res)
#解法三:暴力法,两层循环遍历,执行效率那自然是不用说了,差的不能再差了,差点要超出时间限制了。
class Solution:
    def twoSum(self,nums,target):
        n = len(nums)
        for x in range(n):
            for j in range(x+1,n):
                if nums[j] == target - nums[x]:
                    return x,j
nums = [2,7,11,13]
target = 9
res = Solution().twoSum(nums,target)
print(res)

猜你喜欢

转载自www.cnblogs.com/liangzhenghong/p/10858993.html