两数之和 - 简单
*************
Python
topic: 1. 两数之和 - 力扣(LeetCode)
*************
Give the topic an inspection.
![]() |
How is the weekend? I have been absent the pronunciation practice for about 1 month. That is not good. Let's talk about conments under the posts, vedios and vlogs. People do silly thing. You will see people will type words like ohh this phone is awful under a post, but they never use it. People say that this car is really good and they buy the old-school cars without driving experience. They may ask which car is better or even try them, but then buy the silly ones. There is a slang called you never criticize people because you never wear them shoes.I can easily swear them because I donot want to waste my time walking their journey. Life is never fair, that is it, no big deal, just no fair. Be professional.
Back to the topic. Iterate through the arrat and every two elements are grouped, which means need two loops.
class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""n = len(nums)i = 0while i < n:j = i + 1while j < n:if nums[i] + nums[j] == target:return[i, j]j = j + 1i = i + 1return[]
but in python, range are elegent.
range(stop) # 生成 0 到 stop-1 的整数
range(start, stop) # 生成 start 到 stop-1 的整数
range(start, stop, step) # 生成 start 到 stop-1 的整数,步长为 step
Then the code should be rewrite.
class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""n = len(nums)for i in range(n):for j in range(i + 1, n):if nums[i] + nums[j] == target:return [i, j]return []
![]() |
This is not enough, in a real progect, function is separed.
class TwoSumChecker:def __init__(self, nums, target): # _init_ 是构造函数,可以被直接调用self.nums = nums # 保存到成员变量self.target = target # 可以避免参数重复传递def check_pair(self, i, j):"""检查 nums[i] + nums[j] 是否等于 target"""return self.nums[i] + self.nums[j] == self.targetclass Solution:def twoSum(self, nums, target):checker = TwoSumChecker(nums, target) # 创建检查器实例n = len(nums)for i in range(n):for j in range(i + 1, n):if checker.check_pair(i, j): # 调用检查逻辑return [i, j]return []