概述
题目
传送门:此题链接https://leetcode-cn.com/problems/two-sum/
初解
一拿到就是比较无脑的死算,从前往后先选定一个数字再凑一凑,看看其和是不是所期望的和。
提示1:A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it’s best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
while nums[i] + nums[j] == target:
return ([i,j])
比较无脑的暴力算法,初解的效果很一般,尤其是用时(程序时间复杂度是 O(n^2))。
更好的解答
根据更多的提示,进一步改善。
提示2:So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y ,which is value - x ,where value is the input parameter. Can we change our array somehow so that this search becomes faster?
提示3:The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
keys={}
for index,num in enumerate(nums):
if target-num in keys:
return [index,keys[target-num]]
keys[num]=index
传送门:enumerate() 函数介绍链接
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
最后
以上就是平常篮球为你收集整理的Python实现leetcode 1.两数之和题目初解更好的解答的全部内容,希望文章能够帮你解决Python实现leetcode 1.两数之和题目初解更好的解答所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复