LeetCode——Two Sum

LeetCode刷題之Two Sum

  • 題目簡介
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
  • 示例數組

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
  • 解法code

    1. 暴力解法,兩層循環嵌套,時間複雜度 O(n^2), 空間複雜度 O(1)索引

      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
    2. 使用字典,字典的key爲數值,value爲數組的索引,在每次循環遍歷時,先求出另外一個數的值,判斷字典的key是否包含該值,若是存在,就返回字典對應值得value和當前循環的索引,若是不存在,將當前值和索引添加到字典中去。 時間複雜度 O(n), 空間複雜度 O(n)ci

      class Solution:
      def twoSum(self, nums: List[int], target: int) -> List[int]:
          if len(nums) == 0:
              return "None"
          else:
              dic = {}
              for i in range(len(nums)):
                  anthor_number = target - nums[i]
                  if anthor_number in dic:
                      return dic[anthor_number], i
                  dic[nums[i]] = i
相關文章
相關標籤/搜索