Leetcode -- Two-sum

更新 發佈閱讀 7 分鐘

information

  • linkTwo Sum - LeetCode
  • Description: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.

solution

method 1

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

The function of the outside loop is to traverse nums.

At the fourth line, it judges whether v's complement is in nums. If it is true, it will go in the second loop to find the index of v's complement.

i+1 can avoid getting the same number.

the same idea but a little different ( by myself )

class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, v in enumerate(nums):
if (target-v) in nums and nums.index(target-v) != i:
return [i, nums.index(target-v)]

the same idea but a little different ( by the official solution )

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 i+j == target:
return [i,j]
return []

However, all above are O(n^2).

method 2

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]
hashmap = {}
for i in range(len(nums)):
hashmap[nums[i]] = i
for i in range(len(nums)):
if target-nums[i] in hashmap and hashmap[target-nums[i]] != i:
return [i, hashmap[target-nums[i]]]

In python, dictionary is hashtable. Therefor, it can improve O(n) to almost O(1) when we search it.

method 3

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

This concept is that it tries check elements while inserting them into the hashtable.

In this way, we need to search forward. The clever part is that the previous elements is stored in the hashtable (hashmap),so what we need to do is check if the complement is in hashtable and what is its index. And since the current number hasn't been inserted yet, it avoids retrieving the same number.

留言
avatar-img
留言分享你的想法!
avatar-img
周濡墨的沙龍
18會員
120內容數
有別於未付費的文章,專題區的文章偏向愛情短篇小說,較有戲劇性,篇幅也會較長;未付費文章會偏向極短篇小說,並且以類似散文的手法寫作
周濡墨的沙龍的其他內容
2025/05/06
這篇文章將藉由 2w1h(what、why、how)來介紹如何透過 github 達到更好的團隊合作。 WHAT github 是甚麼 社交媒體有 ig、facebook 等可以分享自己的生活,而 github 則是工程師分享自己 code 或專案的地方。不過,這並不是 github 受歡迎之
Thumbnail
2025/05/06
這篇文章將藉由 2w1h(what、why、how)來介紹如何透過 github 達到更好的團隊合作。 WHAT github 是甚麼 社交媒體有 ig、facebook 等可以分享自己的生活,而 github 則是工程師分享自己 code 或專案的地方。不過,這並不是 github 受歡迎之
Thumbnail
2025/04/23
核心意識 自有平台 工作地點 職缺和實習 培訓 你不需要很厲害 QA 面試詳細內容:20分鐘線上程式測驗。沒有複試,一次面試。會從履歷中問問題 有沒有短期實習,例如暑期實習:希望暑假+一個學期。開學後每周三天沒有硬性規定哪幾天 資安推薦能力或證照:英文能力,e
Thumbnail
2025/04/23
核心意識 自有平台 工作地點 職缺和實習 培訓 你不需要很厲害 QA 面試詳細內容:20分鐘線上程式測驗。沒有複試,一次面試。會從履歷中問問題 有沒有短期實習,例如暑期實習:希望暑假+一個學期。開學後每周三天沒有硬性規定哪幾天 資安推薦能力或證照:英文能力,e
Thumbnail
2025/03/03
此題為栅欄密碼或稱籬笆密碼。會知道栅欄密碼是因為文字中出現fence和zig-zag pattern。其中第二點很符合栅欄密碼的特徵,請看下圖。 栅欄密碼真就是以Z字形進行加密的。 而這題只要放進隨便一個online decrypt tool都可以解出來。例如我就是用這個網站解出來的。欄數填
Thumbnail
2025/03/03
此題為栅欄密碼或稱籬笆密碼。會知道栅欄密碼是因為文字中出現fence和zig-zag pattern。其中第二點很符合栅欄密碼的特徵,請看下圖。 栅欄密碼真就是以Z字形進行加密的。 而這題只要放進隨便一個online decrypt tool都可以解出來。例如我就是用這個網站解出來的。欄數填
Thumbnail
看更多
你可能也想看
Thumbnail
還在煩惱平凡日常該如何增添一點小驚喜嗎?全家便利商店這次聯手超萌的馬來貘,推出黑白配色的馬來貘雪糕,不僅外觀吸睛,層次豐富的雙層口味更是讓人一口接一口!本文將帶你探索馬來貘雪糕的多種創意吃法,從簡單的豆漿燕麥碗、藍莓果昔,到大人系的奇亞籽布丁下午茶,讓可愛的馬來貘陪你度過每一餐,增添生活中的小確幸!
Thumbnail
還在煩惱平凡日常該如何增添一點小驚喜嗎?全家便利商店這次聯手超萌的馬來貘,推出黑白配色的馬來貘雪糕,不僅外觀吸睛,層次豐富的雙層口味更是讓人一口接一口!本文將帶你探索馬來貘雪糕的多種創意吃法,從簡單的豆漿燕麥碗、藍莓果昔,到大人系的奇亞籽布丁下午茶,讓可愛的馬來貘陪你度過每一餐,增添生活中的小確幸!
Thumbnail
題目敘述 Combination Sum II_Leetcode #40 給定一個整數陣列candidates 和 目標值target。 每個陣列元素只能選擇一次,請問有多少種組合方法,可以使得組合數總和 = target? 請把滿足組合數總和 = target的組合方法以陣列的形式返回答案
Thumbnail
題目敘述 Combination Sum II_Leetcode #40 給定一個整數陣列candidates 和 目標值target。 每個陣列元素只能選擇一次,請問有多少種組合方法,可以使得組合數總和 = target? 請把滿足組合數總和 = target的組合方法以陣列的形式返回答案
Thumbnail
題目敘述 Subarray Sums Divisible by K 給定一個整數陣列,請計算有幾個區間和能夠整除k的連續區間? 測試範例 Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7
Thumbnail
題目敘述 Subarray Sums Divisible by K 給定一個整數陣列,請計算有幾個區間和能夠整除k的連續區間? 測試範例 Input: nums = [4,5,0,-2,-3,1], k = 5 Output: 7
Thumbnail
題目敘述 題目會給我們一個鏈結串列的頭部結點Head node,要求我們計算鏈結串列中的Twin sum最大值是多少? 註: Twin Sum的定義就是頭尾結點相對位置相同的,互相配對加總在一起的值。 例如 給定串列= 1 -> 3 -> 2 -> 5 -> 100 -> 8 1, 8 一組
Thumbnail
題目敘述 題目會給我們一個鏈結串列的頭部結點Head node,要求我們計算鏈結串列中的Twin sum最大值是多少? 註: Twin Sum的定義就是頭尾結點相對位置相同的,互相配對加總在一起的值。 例如 給定串列= 1 -> 3 -> 2 -> 5 -> 100 -> 8 1, 8 一組
Thumbnail
題目敘述 題目會給定我們一個整數陣列nums,我們每回合可以挑選總和為K的兩個數字,形成一個K-Sum pair。 請問我們最多可以製造幾個K-Sum pair? 題目的原文敘述 測試範例 Example 1: Input: nums = [1,2,3,4], k = 5 Output
Thumbnail
題目敘述 題目會給定我們一個整數陣列nums,我們每回合可以挑選總和為K的兩個數字,形成一個K-Sum pair。 請問我們最多可以製造幾個K-Sum pair? 題目的原文敘述 測試範例 Example 1: Input: nums = [1,2,3,4], k = 5 Output
Thumbnail
題目敘述 題目會給兩個陣列nums1和nums2。 題目要求我們從中同步選擇長度為k的子序列,並且最大化子序列的分數, 回傳最高的分數值。 分數的定義: 分數 = (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] ,
Thumbnail
題目敘述 題目會給兩個陣列nums1和nums2。 題目要求我們從中同步選擇長度為k的子序列,並且最大化子序列的分數, 回傳最高的分數值。 分數的定義: 分數 = (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] ,
Thumbnail
題目敘述 題目會給我們一個參數k 和 目標值n。 請問我們從1~9內挑k個相異的數字,使得他們的總和為n 的組合數有多少? 挑選時,每個數字必須相異,而且每個數字只能選一次。 題目的原文敘述 測試範例 Example 1: Input: k = 3, n = 7 Output: [
Thumbnail
題目敘述 題目會給我們一個參數k 和 目標值n。 請問我們從1~9內挑k個相異的數字,使得他們的總和為n 的組合數有多少? 挑選時,每個數字必須相異,而且每個數字只能選一次。 題目的原文敘述 測試範例 Example 1: Input: k = 3, n = 7 Output: [
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News