Leetcode(001) 两数之和
题目难度:简单
题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
示例:
解题思想:
使用两次for循环遍历数组,第一次外层循环用来锁定一个元素,第二次内部for循环,遍历第一次锁定元素的后面所有元素。两数相加与target对比,如果成立,返回这两个元素的下标组成的数组。
#python代码实现
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lenth = len(nums)
for i in range(lenth-1):
for j in range(i+1,lenth):
if target == nums[i] + nums[j]:
return [i, j]