1. 程式人生 > 其它 >1. Two Sum(兩數之和)Python

1. Two Sum(兩數之和)Python

技術標籤:LeetCodeleetcode

LeetCode目錄

一、題目

1.Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 103
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

二、解法1:暴力破解法(Brute Force)

分析

從一個數組(nums)中找到兩個數,這兩個數的和等於 target。那麼就可以一個一個地試,從第一個元素開始,判斷後面的數和它相加是否等於target。這裡有個地方需要注意:(1)根據題目 **Only one valid answer exists **的意思,所以必然存在且僅存在一個解。

示例:nums = [2,7,11,15], target = 9

(1)從第 1 個數2開始,逐個與後面的數相加判斷是否等於 9 。

在這裡插入圖片描述

因為 2 + 7 剛好等於9,所以將元素 2 和 7 的索引儲存到列表中,並將該列表返回即可。

(2)因為要返回的是索引,所以迴圈的時候應該使用陣列的索引進行迴圈。

演算法實現

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 暴力破解法
        # len()方法時間複雜度是O(1)
        n = len(nums)
        # 因為要返回的是索引,所以應該使用陣列的索引進行迴圈
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
            

複雜度

  • 時間複雜度:O(n^2)​

  • 空間複雜度:O(1)。

    因為額外的空間只是[i,j],無論陣列多大,都是隻儲存兩個元素,所以時間複雜度是 O(1)。

三、解法2:雜湊表

分析

這題涉及到一個判斷是否存在的問題,判斷是否存在使用雜湊表是最快的,因為時間複雜度是:O(1)。所以可以在遍歷的時候把元素作為鍵,把索引作為值存到字典中。然後遍歷下一個元素 elem 的時候判斷其是否存在於字典中,如果存在,則找到了。

示例:nums = [2,7,11,15], target = 9

(1)遍歷第一個元素2, 不存在於字典中,所以把{2, 0}存到字典中。

dct = {2:0,}

在這裡插入圖片描述

(2)遍歷第二個元素 7,9 - 7 = 2,判斷 2 是否存在於字典中,存在,返回索引,結束遍歷。

在這裡插入圖片描述

演算法實現

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # 雜湊表
        dct = {}
        for i, v in enumerate(nums):
            if target - v in dct:
                return [dct[target - v], i]
            dct[v] = i

複雜度

  • 時間複雜度:O(n)​
  • 空間複雜度:O(n)。

四、資料結構與演算法

資料結構

1、順序表:list

2、雜湊表:dict

演算法

1、暴力破解法。

LeetCode目錄