【LeetCode刷题1】两数之和

1、两数之和

leetcode链接:https://leetcode.cn/problems/two-sum/

给定一个整数数组 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 < = n u m s . l e n g t h < = 1 0 4 2 <= nums.length <= 10^4 2<=nums.length<=104
  • − 1 0 9 < = n u m s [ i ] < = 1 0 9 -10^9 <= nums[i] <= 10^9 109<=nums[i]<=109
  • − 1 0 9 < = t a r g e t < = 1 0 9 -10^9 <= target <= 10^9 109<=target<=109
  • 只会存在一个有效答案

进阶: 你可以想出一个时间复杂度小于 O ( n 2 ) O(n^2) O(n2) 的算法吗?

方法一:i, j 都顺序遍历

def twoSum(nums, target):
    lens = len(nums)
    for i in range(lens):  # 0 1 2 ... lens-1
        for j in range(lens)[i + 1:]:  # 1 2 ... lens-1
            if nums[i] + nums[j] == target:
                return [i, j]
            else:
                continue

方法二:i 顺序遍历, j 逆序遍历

def twoSum(nums, target):
    lens = len(nums)
    for i in range(lens): # i 顺序遍历
        for j in range(lens)[lens - 1:i:-1]: # j 逆序遍历
            if nums[i] + nums[j] == target:
                return [i, j]
            else:
                continue

方法三:index()查看索引

def twoSum(nums, target):
    lens = len(nums)
    for i in range(lens):
        temp = target - nums[i]  # temp为差值(目标值-元素值)
        if nums[i] == temp:  # 对半分情况:[3, ...] target = 6 或 [4, ...] target = 8
            if nums.count(temp) >= 2:  # 多个差值:[3, 3, ...] target = 6 直接从i后面开始索引
                j = nums.index(temp, i + 1)
                return [i, j]
            else:  # 一个插值, continue下一个循环
                continue
        else:  # 不存在对半分情况
            if temp in nums:  # 直接索引
                j = nums.index(temp)
                return [i, j]
            else:  # 下一个循环
                continue
             return [i, j]
            else:  # 下一个循环
                continue

猜你喜欢

转载自blog.csdn.net/m0_70885101/article/details/127566904