[Leetcode] 1. Two Sum

閱讀時間約 1 分鐘

完整題目: 1. Two Sum Easy

  • Given an array of integersnums 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]

Explanation: 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]


  1. 暴力解O(n2)

使用2個for迴圈,如果有遇到2個數加起來等於target,則回傳index

暴力解

暴力解


  1. NeetCode解法

參考影片 : https://www.youtube.com/watch?v=KLlXCFG5TnA

NeetCode 解題方法

NeetCode 解題方法












7會員
47內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!
Youna's Devlog 的其他內容
[Leetcode] 242. Valid Anagram
閱讀時間約 3 分鐘
[Leetcode] 217. Contains Duplicate
閱讀時間約 2 分鐘
你可能也想看
集合操作: 尋找兩個陣列的差異值Diff of Two Arrays_Leetcode #2215 精選75題解析 題目敘述 題目會給定我們兩個整數陣列作為輸入nums1, nums2,要求我們找出兩個陣列的差異值。 找出在nums1但是不在nums2的元素,以陣列的形式放在answer[0]輸出。 找出在nums2但是不在nums1的元素,以陣列的形式放在answer[1]輸出。 題目的原文敘述
Thumbnail
avatar
小松鼠
2024-02-29
一魚多吃 用DP來數有幾個bit 1_Counting Bits Leetcode #338 精選75題題目敘述 題目會給定我們一個n值,要求我們列出從0 ~ n 之間,每個整數有幾個bit1,以陣列的形式返回答案。 例如n=3時 因為 0 = 0b 0 1 = 0b 1 2 = 0b 10 3 = 0b 11 輸出答案為[0, 1, 1, 2] 題目的原文敘述 測試範例 E
Thumbnail
avatar
小松鼠
2024-02-15
矩陣0與1的差值 Leetcode 2484 Diff Between 1s and 0s in Row and Col題目敘述 題目會給定我們一個二元矩陣grid,要求我們計算這個矩陣的Difference值,並且以矩陣的形式返回答案。 對於grid[i][j] 的Difference值定義 = 同一個row i裡面 1的數目 + 同一個column j裡面 1的數目 - 同一個row i裡面 0的數目
Thumbnail
avatar
小松鼠
2023-12-14
最大兩數的乘積 Leetcode 1464 Max Product of Two Elements in Array題目敘述 題目會給定一個整數陣列nums,要求我們找出最大的兩個整數a, b,返回(a-1) * (b-1)的乘積。 詳細的題目可在這裡看到 測試範例 Example 1: Input: nums = [3,4,5,2] Output: 12
Thumbnail
avatar
小松鼠
2023-12-12
二進位操作 計算bit1的數目 Number of 1 Bits_Leetcode #191題目敘述 題目會給我們一個整數,要求我們計算出這個整數的二進位表示法裡面,有幾個bit1? 例如 5 = 二進位的 101 => 有2個 bit1,答案為2 英文版的題目敘述在這裡
Thumbnail
avatar
小松鼠
2023-11-29
經典 字典應用題 兩數之和 Two Sum_Leetcode #1題目敘述 題目會給我們一個陣列,要求我們返回 兩數之和=target所在的陣列索引值。 題目還額外保證,一定剛好有一組解。 測試範例 Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Thumbnail
avatar
小松鼠
2023-11-21
排序應用題 Sort Integers by The Number of 1 Bits Leetcode #1356題目會給定一個存有整數的陣列,要求我們依照下列規則進行排序,由小排到大,升序排列。
Thumbnail
avatar
小松鼠
2023-10-30
位元操作 應用題 判斷輸入是否為2^k 二的冪 Leetcode 231: Power of Two這題的題目會給我們一個輸入整數,要求我們判斷這個整數是否可以用2^k 的形式來表達 (二的冪)?
Thumbnail
avatar
小松鼠
2023-10-23
經典串列題 合併已排序好的兩條串列 Merge Two Sorted Lists Leetcode #21題目會給我們兩條已經從小到大排序好的串列,要求我們依照從小到大的順序,合併這兩條串列。
Thumbnail
avatar
小松鼠
2023-10-03
【LeetCode】167. Two Sum II 題目如下: Input: numbers = [2,7,11,15], target = 9 Output: [1,2]
Thumbnail
avatar
2021-10-07