Leetcode1——两数之和

作者: 皮皮大 | 来源:发表于2019-09-29 07:29 被阅读0次

题目

在给定的数组中,找出两个数相加之和等于目标数target,返回两个数的下标index1,index2

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Python代码

# 暴力求解:两层for循环,最容易实现

class Solution:
    def twoSum(self, List, target):
        n = len(List)
        for i in range(n):
            # 注意:数据不能重复,下标i前面的数据不能再次使用
            for j in range(i+1, n):
                if List[i] + List[j] == target:
                    return i,j
        
twosum = Solution()
twosum.twoSum([2, 7, 11, 15], 9)
# 一层for循环,另一个if语句通过减法实现,和暴力破解比较类似

class Solution:
    def twoSum(self, List, target):
        n = len(List)
        for i in range(n):
            if target - List[i] in List:
                return [i, List.index(target-List[i])]
            else:
                continue

twosum = Solution()
twosum.twoSum([2, 7, 11, 15], 9)

优化方式

  • 巧妙利用enumerate函数
class Solution(object):
    def twoSum(self, nums, target):
        d = {}
        for i, num in enumerate(nums):  # enumerate函数同时返回:索引和列表中的值
            if target - num in d:
                return [d[target - num], i]  # 如果另一个元素在字典中,返回的是另一个元素的值value,也就是索引,同时还有i
            else:
                d[num] = i   #  若不在字典中,则主动往字典中添加元素,k-v满足"num":i,此时字典中的值就是索引
                # print(d)

        
twosum = Solution()
print(twosum.twoSum([2, 11, 7, 15], 9))
# 通过字典形式
class Solution:
    def twoSum(self, List, target):
        dic = {}  # 定义空字典
        for i in range(len(List)):  # 遍历长度
            if List[i] not in dic:
                dic[target - List[i]] = i + 1  
            else:
                return dic[List[i]] - 1, i

        return -1, -1
    
twosum = Solution()
twosum.twoSum([2, 11, 7, 15], 9)

相关文章

  • Leetcode1——两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重...

  • leetCode1两数之和

    1 两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同...

  • Leetcode1——两数之和

    题目 在给定的数组中,找出两个数相加之和等于目标数target,返回两个数的下标index1,index2 Pyt...

  • Tag【数组】 —— LeetCode1 两数之和

    题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并...

  • 两数之和(golang)

    原题:两数之和 关联:两数之和 II - 输入有序数组(golang)两数之和 IV - 输入 BST(golang)

  • 两数之和 II - 输入有序数组(golang)

    原题:两数之和 II - 输入有序数组 关联:两数之和(golang)两数之和 IV - 输入 BST(golan...

  • 浅入浅出实现一个异步求和函数

    简化:两数之和 我们先来简单的实现一个异步两数之和函数 加深:多数之和 上面我们实现了两数之和,然后扩展到多数之和...

  • 两数之和,三数之和

    转载:https://www.cnblogs.com/DarrenChan/p/8871495.html 1. 两...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

网友评论

    本文标题:Leetcode1——两数之和

    本文链接:https://www.haomeiwen.com/subject/jiiryctx.html