1. Two Sum

https://leetcode.com/problems/two-sum/description/

Solution

  • Brute Force

    • Use every element as an anchor and search its right element

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

时间复杂度:O(n^2) 空间复杂度:O(1)

  • Hash Map

    • Leverage the power of hashmap and store the number and its index in the map

    • When the map contain target - curNum, we know the search is complete

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        residual_dict = {}

        for i, num in enumerate(nums):
            if num in residual_dict:
                return [residual_dict[num], i]
            else:
                residual_dict[target - num] = i

时间复杂度:O(n) 空间复杂度:O(n)

Last updated