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.ide
給定一個整數數組,返回兩個數的指數,他們加起來是一個具體的目標。你可能認爲每一個輸入一個解決方案,你可能不會使用相同的元素兩次。code
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].排序
先將數組排序ci
而後遍歷數組,找到一個比他小的數element
肯定另外一個數的位置,若是不存在,繼續尋找get
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ b = sorted(nums) for i in b: o = target - i if o not in nums: continue i_index = nums.index(i) for idex, item in enumerate(nums): if item == o and idex != i_index: return sorted([i_index, idex])