【难度】简单
【题目】来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
【思路】遍历数组,先定位到一个数x,然后再遍历数组,从数组中的其他数找到y,使target-x=y(或x+y=target)
【代码】
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)):
if target - nums[i] == nums[j]:
return [i,j]
【解释】
网站写好了开头
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
这行代码已经定义了数组nums和target,所以不需要再一次地定义。
【笔记】
(1)输入数组
nums=[int(n) for n in input().split()]
(2)解释双重循环
for i in range(len(nums)):
for j in range(i+1,len(nums)):
第一重循环是重头开始遍历数组中的元素,第二重循环
是从第一重循环定位的元素的下一位开始遍历。
【优化】
(PS:参考网络上的代码)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
if target - nums[i] in nums:
if i!= nums.index(target - nums[i]): #第二个判断条件:同一个元素不能使用两遍
return[i,nums.index(target-nums[i])]
使用了list+in的方法来优化,用in去查找数组中的元素
【其他】
因为我还没有看过数据结构和算法的知识,所以暂时不能用哈希表之类的方法求解,等我有了这方面的知识以后,会继续回来补充