关闭

1_twoSum

标签: leetcode
142人阅读 评论(0) 收藏 举报
分类:

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)
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65379次
    • 积分:2033
    • 等级:
    • 排名:第19809名
    • 原创:135篇
    • 转载:52篇
    • 译文:0篇
    • 评论:23条
    博客专栏