首页 > 其他 > 详细

每天一道面试题LeetCode 01 -- 两数之和

时间:2019-10-28 23:47:21      阅读:83      评论:0      收藏:0      [点我收藏+]

Two Sum 两数之和

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

技术分享图片

解题思路

1、暴力解法:利用两层循环,比如i从0:len(nums),j从i+1:len(nums),如果i + j == target,则说明找到了,返回i和j,否则返回空。但复杂度为$ o\left( n^2 \right) $
2、用字典模拟哈希求解,遍历列表同时查字典。复杂度为$ o(n) $

代码

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for index, val in enumerate(nums):
            m = target - val
            if m in dic:
                return(dic[m], index)
            else:
                dic[val] = index

每天一道面试题LeetCode 01 -- 两数之和

原文:https://www.cnblogs.com/yuzhou-1su/p/11755795.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!