leetcode 1.Two sum

题目描述

https://leetcode.com/problems/two-sum/

解决方法

一:

class Solution(object):
    def twoSum(self, nums, target):
        len_nums = len(nums)
        for i in range(len_nums):
            for j in range(i+1,len_nums):
                if i != j and nums[i]+nums[j]==target:
                    return [i,j]

复制列表内容
L = [1,2,3]
LL = L.copy() 或LL = L[:]

二:

class Solution(object):
    def twoSum(self, nums, target):
        nums_back = nums[:]
        nums.sort(reverse = False)
        print(nums)
        lens = len(nums)
        i = 0
        j = lens-1
        end = False
        while not end:
            test = nums[i] + nums[j]
            if test > target:
                j = j -1
            elif test < target:
                i = i + 1
            else:
                end = True
                m = nums_back.index(nums[i]) //由于列表value可能相同,而坐标不同,通过index会读出相同的坐标值
                n = nums_back.index(nums[j])
        return [m,n]

三:

class Solution(object):
    def twoSum(self, nums, target):
        m = {}
        for i in range(len(nums)):
			end = target - nums[i]
			if end not in m.keys():
				m[nums[i]] = i
			else:
				return [m[end], i]

第三种可以解决第二种,由于值相同而列表读取坐标相同的问题
即如果前面有两个数相加为target,那么必有两次减法的值存在于原有的list中,尤其是第二次减的时候

原文地址:https://www.cnblogs.com/sojrs/p/10976323.html