准备开始刷leetcode上的算法题,并对相关内容进行记录
今天记录的是leetcode上编号为1的题目TwoSum
leetcode链接如下:https://leetcode.com/problems/two-sum/
题目描述:给定一个只包含整数的数组,返回由数组中两个数相加之和为target的下标,假定该数组中有且只有一个解,且每个元素只能使用一次
举例: nums=[2, 7, 11, 15], target = 9,
返回[0,1]
解题思路:
思路一:暴力解法,两次循环,复杂度n^2,不能通过
思路二:新建一个字典,将元素放进去,查找target-x是否在字典中,复杂度n
以下给出了思路二的解法
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ret = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
ret = [i, j]
return ret
return ret