问题

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:
    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])

努力奋斗的小菲菲
23 声望3 粉丝

小鲜肉一枚