two sum[easy]

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].
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <2:
            if nums[0] != target:
                return "no this"
            return [0]
        else:
            nums_new = nums
            for i in range(len(nums_new)):
                if target-nums_new[i] in nums_new[i+1:]:
                    return [i,nums_new.index(target-nums_new[i],i+1)]
            return False
        
result=Solution().twoSum([14,3,5,6,3],6)        
print(result)
posted @ 2017-09-18 14:42  Dus  阅读(150)  评论(0编辑  收藏  举报