Leetcode sum of two numbers (Python native)

Question: Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.

You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.
Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums[0] + nums[1] = 2 + 7 = 9,
it returns [0, 1].
Here we provide two solutions and the first solution to achieve the result on a local tool
(using a list, looping judgment, more time-consuming) :

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        x = len(nums)  #获取列表长度,准备循环计算
        for i in range(x):
            j = target-nums[i]
            if j in nums:
                x = nums.index(j)
                if x != i:
                    return i,x

Option two (reference dictionary greatly reduces time complexity):

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
       dict={
    
    }  #定义一个字典

       for i,element in enumerate(nums):
            if target-element in dict:
               return [dict[target-element],i]
            dict[element] = i  

To run the leetcode questions locally, you need to pay attention to adjusting the parameters after the function (as shown in the figure)
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45701131/article/details/106461911