Leetcode sum of two numbers - hash solution

0 topic description

Link to Leetcode original title: Sum of Two Numbers
Insert picture description here

1 Violent enumeration

The easiest way to think of is to enumerate every number x in the array to find whether there is target-x in the array.
When we use the method of traversing the entire array to find target-x, we need to note that every element before x has already been matched with x, so there is no need to match. Each element cannot be used twice, so we only need to look for target-x in the elements after x.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

Complexity analysis
Time complexity: O (N 2) O(N^2)O ( N2 ), whereNNN is the number of elements in the array. In the worst case, any two numbers in the array must be matched once.
Space complexity:O (1) O(1)O ( 1 )

2 hash table

Note that the reason for the high time complexity of method 1 is that the time complexity of finding target-x is too high. Therefore, we need a better method that can quickly find whether the target element exists in the array. If it exists, we need to find its index.
Using a hash table, the time complexity of finding target-x can be reduced to O (N) O(N)O ( N ) decreases toO (1) O (1)O ( 1 ) .
In this way, we create a hash table. For each x, we first query whether target-x exists in the hash table, and then insert x into the hash table to ensure that x will not match itself.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict()
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i
        return []

Complexity analysis
Time complexity: O (N) O (N)O ( N ) , whereNNN is the number of elements in the array. For each element x, we canO (1) O(1)Look for target-x O ( 1 ) .
Space complexity:O (N) O(N)O ( N ) , whereNNN is the number of elements in the array. Mainly the overhead of the hash table.

Reference

leetcode-sum of two numbers

Guess you like

Origin blog.csdn.net/OuDiShenmiss/article/details/109256525