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

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) $ ,空间复杂度 $ o(1) $

2、对暴力解法进行改进,已知target,所以其实只需要遍历一遍i就行,查看j == target - i是否在字典中。查找的话可以利用到hashmap,用字典模拟哈希求解,遍历列表同时查字典。

复杂度分许:时间复杂度为 $ o(n) $ ,空间复杂度也为 $ o(n) $

思路一代码

def twoSum_baoli(nums, target):
    length = len(nums)
    if length < 2:
        return None
    for i in range(length):
        for j in range(i+1, length):
            if nums[i] + nums[j] == target:
                return [i, j]
    return None

思路二代码

def twoSum(nums, target):
    hash_map = dict()
    for i, x in enumerate(nums):
        if target - x in hash_map:
            return [i, hash_map[target - x]]
        hash_map[x] = i
posted @ 2019-10-28 21:49  宇宙之一粟  阅读(179)  评论(0编辑  收藏  举报