1_twoSum

来源:互联网 发布:常用 windows api 编辑:程序博客网 时间:2024/05/19 20:42

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]        """        length = len(nums)        for i in range(length):            for j in range(i,length):                need = target - nums[i]                if i != j and nums[j] == need:                    return (i,j)
原创粉丝点击