【LeetCode】Two Sum

来源:互联网 发布:金太阳教育软件 编辑:程序博客网 时间:2024/06/06 20:20

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.

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

我的理解是给定一个列表和一个定值,然后在列表中查找有没有两个数相加等于定值,返回在列表中这两个数的下标
开始我尝试暴力解法,但是py3不支持

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

然后尝试另一种解法

    class Solution(object):        def twoSum(self, nums, target):        """            :type nums: List[int]            :type target: int            :rtype: List[int]        """            if len(nums)<=1:                return False            for i in range(len(nums)):                m=target-nums[i]                if m in nums:                    mIndex=nums.index(m)                    if mIndex==i:                        i+=i                    else:                        return [i,mIndex]

成功!

原创粉丝点击