leetcode 1.Two sum

Posted sojrs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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中,尤其是第二次减的时候

以上是关于leetcode 1.Two sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 1.Two sum

Leetcode 1. Two Sum (Python)

LeetCode #1 - Two Sum

1. 两数之和 [leetcode 1: Two Sum]

1. 两数之和 [leetcode 1: Two Sum]

Leetcode-1 Two Sum