leetcode-easy-两数之和
两数之和一
解题思路: 使用循环的方法从前到后计算给出的数组,直到找到目标
题目
# 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
# 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
# 你可以按任意顺序返回答案。
#
# 示例 1:
# 输入:nums = [2,7,11,15], target = 9
# 输出:[0,1]
# 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
#
# 示例 2:
# 输入:nums = [3,2,4], target = 6
# 输出:[1,2]
#
# 示例 3:
# 输入:nums = [3,3], target = 6
# 输出:[0,1]
#
#
# 提示:
# 2 <= nums.length <= 104
# -109 <= nums[i] <= 109
# -109 <= target <= 109
# 只会存在一个有效答案
#
#
# 进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
# Related Topics 数组 哈希表
# 👍 11630 👎 0
代码:
方法一 暴力破解
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
a=[0,0]
i=j=0
for i in range(0,len(nums)) :
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
a[0] = i
a[1] = j
return a
# leetcode submit region end(Prohibit modification and deletion)
方法二 遍历查找target - nums[i]是否在nums中
for i in range(0,len(nums)) :
n=target - nums[i]
for j in range(i+1,len(nums)):
if n == nums[j]:
return [i,j]
执行耗时:1688 ms,击败了24.59% 的Python3用户
内存消耗:15.2 MB,击败了42.35% 的Python3用户
##方法三 思想同方法二 用到了 num in nums 确认存在方法 和 nums.index() 返回下标方法
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)):
num = target - nums[i]
temp = nums[:i]
if num in temp:
j = nums.index(num)
return [i,j]
执行耗时:372 ms,击败了33.17% 的Python3用户
内存消耗:15.2 MB,击败了39.10% 的Python3用户
你做的每件事都值得。
——yaerda