写在前面
鉴于目前找不到工作,决定在压力之余,一刷Leetcode,hhhh,要转行但是没有实习过的小伙伴加油呀,不然我就是前车之鉴!(20届秋招开始,感到了压梨)在网上话有点多hhhh,希望 ( 跪求)有(大)伙伴一起每晚刷题,接下来请看~
题目描述
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)
链接:https://leetcode-cn.com/problems/two-sum
题目分析
- 参数: List, target
- 需求: 分析List中是否存在两个数,相加等于 target
- 期待: 有则返回两个index,没有就返回 -1
思路如下:
- 暴力破解法:通过双重循环来遍历所有组合,看是否会得到目标结果,代码如下:
class Solution:
def twoSum(self, nums, 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
return -1
采用暴力破解法:简单粗暴,在没有思路的时候不失为一个解决问题的办法,但是其有一个很大的缺点就是时间复杂度太高,达到了O(n^2),到这里我们就要做个思考中的宝宝了,碰见O(n^2),要想办法看能不能化为O(nlogn),甚至O(n)。刚想说明天再码,突然灵机乍现,哎呀女朋友打电话了,灵感也没有了,兄弟们加油,还是明天再码。