topic

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target, and return their array indices.

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

brute force enumeration

Two layers of for loops are traversed one by one, O(n^2)

def twoSum(ary,target):
    for i in range(len(ary)):
        for j in range(i+1,len(ary)):
            if ary[i]+ary[j]==target:
                return [i,j]
    return []

Dictionary simulation hash table

A layer of for loop traversal, the element value is the key and the table below is the value stored in the dictionary. O(n)

def twoSum(ary,target):
    hashTable = {}
    for i, num in enumerate(ary):
        if target-num in hashTable:
            return [hashTable[target-num],i]
        hashTable[num]=i
    return []

Ethan
140 声望11 粉丝

水平较低,只是记录,谨慎参阅


引用和评论

0 条评论