题目:

方法1:
暴力算法,直接循环套循环。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = list()
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if target == nums[i] + nums[j]:
result.append(i)
result.append(j)
return result方法2:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result = list()
nums_1 = nums.copy()
i = 0
while len(nums) > 0:
pop = nums.pop(0)
jj = nums_1[i]
nums_1[i] = 'x'
if target - pop in nums_1:
nub = nums_1.index(target - pop)
if i != nub:
result.append(i)
result.append(nub)
break
nums_1[i] = jj
i += 1
return result一次循环求差,然后在给定的list中寻找是否有相同值出现,求其index。
有一个小技巧是可以先用x代替原始元素。
只需要一次循环就可完成,在时间复杂度上优于第一种算法。
本文介绍了如何使用Python解决LeetCode中的Two Sum问题。分别讲解了暴力求解方法,即双重循环实现,以及更优的一次循环解决方案,通过计算差值并在列表中查找匹配项,提高效率。

293

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



