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].
  • 解法

    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)

      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

einherjar
32 声望9 粉丝

练好基本功,方能打开任督二脉。


引用和评论

0 条评论