leetcode1 Two sum【基础题】【Python刷题】


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



你可能感兴趣的:(###基本算法(~,o,~)Y,面试,笔试,python)