The number of algorithms and two python version

A method, violent solution - 5s
Complexity Analysis: time complexity: O (^ 2 n) space complexity: O (1)
length = len(nums)
for i in range(length):
    for j in range(i + 1, length):
        if nums[i] + nums[j] == target:
            return [i, j]
Method 2: Using python slice - 1s
Complexity Analysis: time complexity: complexity of O (n) space: O (1)

The main key to solving problems is to find num2 = target - num1, also list whether in fact the same principle with 2 traversal
for i in range(len(nums)):
    if target-nums[i] in nums[i+1:]:
        return [i, nums.index(target-nums[i], i+1)]
Method three: Hash - 80ms
Complexity Analysis: time complexity: complexity of O (n) space: O (n)

Immediate needs of hashes record key, is to find the need to traverse values:
dic = {}
for i, num in enumerate(nums):
    if num in dic:
        return [dic[num], i]
    else:
        dic[target - num] = i
Author: aver58
link: https: //leetcode-cn.com/problems/two-sum/solution/1liang-shu-zhi-he-by-aver58/
Source: stay button (LeetCode)
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/strawberry-1/p/11491663.html