0
点赞
收藏
分享

微信扫一扫

leetcode解题心路1-两数之和

盖码范 2022-01-31 阅读 14

两数之和

问题

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

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

示例

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

输入:nums = [3,2,4], target = 6
输出:[1,2]

输入:nums = [3,3], target = 6
输出:[0,1]

二、解题步骤

1.遍历

对于每一个元素都与其他元素相加,并判断是否为target,是的话返回下标。

class Solution(object):
    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]

2.Target - 元素

用Target逐个 - 列表中的元素,判断差是否在列表中,并返回下标

class Solution(object):
    def twoSum(self, nums, target):
        for i in range(len(nums)):
            j = (target-nums[i])
            if j in nums :
                if nums.index(j) != i :
                    return [i,nums.index(j)]

下一题 两数相加

举报

相关推荐

LeetCode 1 两数之和

【LeetCode】1两数之和

Leetcode 1:两数之和

LeetCode-1-两数之和

LeetCode1.两数之和

【LeetCode】1. 两数之和

LeetCode 1.两数之和

0 条评论