【LeetCode】Two Sum
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]
成功!
还没有评论,来说两句吧...