iT邦幫忙

2025 iThome 鐵人賽

DAY 1
0
自我挑戰組

leetcode系列 第 1

leetcode 1. Two Sum

  • 分享至 

  • xImage
  •  

今天要分享的題目是最簡單的
題目:
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.

中文翻譯就是:
給定一個整數數組nums 和一個整數target,傳回兩個數字的索引,使得它們加起來等於target。

您可以假設每個輸入只有一個解決方案,並且您可能不會兩次使用相同的元素。

您可以按任意順序返回答案。

程式碼:
https://ithelp.ithome.com.tw/upload/images/20250915/20169340hQewmgMIYL.png

Two Sum 運行思路

1.建立一個 HashMap

用來記錄「數字的值」和「它出現的索引」。

方便快速查找「某個數字是否已經看過」。

2.逐一掃描陣列 nums

從索引 i = 0 開始,一個一個處理。

3.計算需要的「另一半」數字

complement = target - nums[i]

這代表:要湊成 target,除了目前的 nums[i],還需要 complement。

4.檢查另一半是否已經出現過

在 HashMap 中查找 complement:

如果存在 → 代表之前的某個元素 + 現在的元素 = target

直接回傳 [之前的索引, 現在的索引]

如果不存在 → 代表還沒湊齊,繼續往下走

5.把目前的元素存進 HashMap

map.put(nums[i], i)

這樣下一個數字就能查到它

6.持續重複直到找到答案

題目保證一定有解,所以一定能在某一步找到並回傳


下一篇
leetcode 2. Add Two Numbers
系列文
leetcode4
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言