Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。
怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~
一、题目描述:
-
题目内容
-
题目示例
-
题目解析
- 题目要求在一个整数数组中,找两个元素值相加与目标值target一样
- 返回的内容为两个元素的坐标组成的数组
二、思路分析:
我们拿到本文,思绪万千。最简单的方法就是for循环暴力求解。
- 第一个for循环,取第一个元素坐标点x
- 第二个for循环,取第二个元素坐标点y
- 判断当nums[x] + nums[y] == target 时,则返回[x,y]坐标点
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n=len(nums)
for x in range(n):
for y in range(x+1,n):
if nums[x]+nums[y] == target:
return [x,y]
break
else:
continue
我们使用两个for循环进行遍历,比较就可以轻松得到结果。但是时间复杂度O(n^2)比较低效
那我们对上述的代码进行优化改善一下,使用一个for循环来解决问题
- 同理,我们需要for循环遍历列表取出元素nums[x]
- 借助字典 key-value 形式来记录nums元素和其坐标位置
- 当target-nums[x]在字典中,则返回取出dict[target-nums[x]]的值和x
根据上述思路,我们使用Python进行实现
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n=len(nums)
dic={}
for x in range(n):
if target-nums[x] in dic:
return dic[target-nums[x]],x
dic[nums[x]]=x
三、拓展练习:
本题,只要求输出符合target一组数组的坐标。哪我们要看一下,符合target的有多少组坐标呢?
带着好奇心,我们带着需求进行练习。
我们直接对上述代码,进行改造,即可实现:
- 引入一个列表专门存储符合target的坐标列表
- return [dic[target - nums[x]], x 替换成L.insert(0,[dic[target - nums[x]], x])
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
dic = {}
L = []
for x in range(n):
if target - nums[x] in dic:
L.insert(0,[dic[target - nums[x]], x])
dic[nums[x]] = x
print(L)
四、总结:
本题提交代码,运行情况如下
第一种方法:时间复杂度为O(n^2),空间复杂度为O(1) 第二种方法:时间复杂度为O(n),空间复杂度为O(1)
以上是本期内容,欢迎大佬们点赞评论,下期见~~~