声明:
如标题所示,因本人为AI路上的新手,文章仅用于辅助个人的整理记忆,理解难免有偏差之处,都是个人拙见,如给其他同僚造成困扰,还请见谅,非常非常非常欢迎私信共同讨论,共同进步
题目描述如下:
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].
因题目理解起来不难,少废话,直接上代码
下面给出两种解法,第一种为本人所写,原理简单,但时间复杂度难以接受,就作为刚开始的一个处女作吧,第二种为参考LeetCode上同僚所写,加之个人理解,呈现给大家,但时间复杂度和空间复杂度也差强人意,作为开拓思路的参考,一点毛病没有
法一:
class Solution:
def f(self, nums, target):
"""
应题目要求,满足列表中的两个元素的加和等于target,
且这两个元素不能重复,所以即是一个组合问题,
设计两个循环,每次分别取不同的两个元素,
外层循环每次移动向右移动一个元素,
内层循环在外层循环之后的一个元素开始遍历列表,
直到找到符合条件的两个元素,
返回其索引值即可
"""
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
时间空间复杂度如下:
- Runtime: 6460 ms, faster than 5.01% of Python3 online submissions for Two Sum.
- Memory Usage: 14 MB, less than 65.81% of Python3 online submissions for Two Sum.
法二:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}#新建一个空的字典
for i, n in enumerate(nums):#借用enumerate函数,可以方便的既遍历列表中的元素,同时又记录了元素的索引
m = target - n#核心思想,用target - n 就可以找出另一个数
if m not in d:#其实首次判断,只是为了将nums中的第一个元素存入字典
d[n] = i#如果n不是要找的那个数,则将n连同索引以键值对的形式存入字典,以便下次遍历到所要找的数,可以查询
else:
return [d[m], i]#返回题目要求,此时m其实是前已存入字典的元素n的值
时间空间复杂度如下:
- Runtime: 48 ms, faster than 78.52% of Python3 online submissions for Two Sum.
- Memory Usage: 14.3 MB, less than 51.16% of Python3 online submissions for Two Sum.
这篇博客主要介绍了LeetCode上的1. Two Sum问题,作者分享了作为AI新手的解题思路,包括两份Python3代码实现。第一种方法虽然简单但时间复杂度较高,而第二种方法在时间和空间效率上有所提升。
&spm=1001.2101.3001.5002&articleId=104992498&d=1&t=3&u=2820ba6c6b9647599d3386deeaaf992e)
1万+

被折叠的 条评论
为什么被折叠?



