话不多说上题目:
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].
简单来说就是给定一个数组nums和一个确定的数字target判断是否能将数组里的两个数相加得到target这个数,并将两个数的位置用一个数列输出。
第一种方法很简单,直接上暴力算法,有时候会超时有时候不会:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
h_len = len(nums)
for i in range(h_len):
for j in range(i+1,h_len):
if nums[i] + nums[j] == target:
return [i,