天天一道面試題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=2python

解題思路

一、暴力解法:利用兩層循環,好比i從0:len(nums),j從i+1:len(nums),若是i + j == target,則說明找到了,返回i和j,不然返回空。less

複雜度分析:時間複雜度爲 $ o\left( n^2 \right) $ ,空間複雜度 $ o(1) $code

二、對暴力解法進行改進,已知target,因此其實只須要遍歷一遍i就行,查看j == target - i是否在字典中。查找的話能夠利用到hashmap,用字典模擬哈希求解,遍歷列表同時查字典。blog

複雜度分許:時間複雜度爲 $ o(n) $ ,空間複雜度也爲 $ o(n) $ci

思路一代碼

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
相關文章
相關標籤/搜索