LeetCode question: Sum of two numbers-2023/9/11

LeetCode question: sum of two numbers

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

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, [0, 1] is returned.
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

First time answer:

class Solution:
    def twoSum(self, nums,target):
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if nums[i] + nums[j]== target:
                    return [i,j]

Time details: 3160ms beats 13.17% of users using Python3
Memory details: 16.16MB beats 96.35% of users using Python3

おすすめ

転載: blog.csdn.net/weixin_53909748/article/details/132814454