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.
给出一个整数数组,返回两个加起来等于特定的目标的两个数的下标。
你可以假定每一个输入都会有一个精确的解答,并且你也许不会两次使用相同的元素。
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
# -*- coding:utf-8 -*-
class Solution(object):
def twoSum(self, nums, target):
# 以 k 为指针
k = 0
# 遍历 nums list
for i in nums:
# j 为另一个数
j = target - i
# 指针后移
k += 1
# rest_nums 为 nums 的剩余部分
rest_nums = nums[k:]
# 如果 j 在 rest_nums 中
if j in rest_nums:
# 则返回 i 和 j 的下标
return [k-1, rest_nums.index(j) + k]
if __name__ == '__main__':
print(Solution().twoSum((2, 7, 11, 15), 17))