概述
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
十分愚蠢的错误QAQ
开始写成了
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans=[]
for i in range(len(nums)):
if(nums.count(target-nums[i])>0 ):
ans.append(i)
ans.append(nums.index(target-nums[i]))
break
return ans
发现这样会出现 [3,2,4] 6输出[0,0] 不满足use the same element twice.
后来改成了
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans=[]
for i in range(len(nums)):
if(nums.count(target-nums[i])>0 and target-nums[i] <>nums[i]):
ans.append(i)
ans.append(nums.index(target-nums[i]))
break
return ans
会出现[3,3]6什么都不输出QAQ
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans=[]
for i in range(len(nums)):
if(nums.count(target-nums[i])>0 and nums.index(target-nums[i]) <>i):
ans.append(i)
ans.append(nums.index(target-nums[i]))
break
return ans
这么简单的题写这么多遍才过QAQ
最后
以上就是慈祥面包为你收集整理的leetcode1 Two sum【基础题】【Python刷题】的全部内容,希望文章能够帮你解决leetcode1 Two sum【基础题】【Python刷题】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复