【LeetCode brush question 1】Sum of two numbers

1. The sum of two numbers

Leetcode link: https://leetcode.cn/problems/two-sum/

Given an array of integers numsand an integer target value , please find the two integers that sum to the target valuetarget in the array and return their array subscripts. target

You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

# 示例 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]

hint:

  • 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
  • There can only be one valid answer

Advanced: You can come up with a time complexity less than O ( n 2 ) O(n^2)O ( n2 )Algorithms?

Method 1: Both i and j traverse sequentially

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

Method 2: i traverse in order, j traverse in reverse order

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

Method 3: index() to view the 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

Guess you like

Origin blog.csdn.net/m0_70885101/article/details/127566904