iT邦幫忙

2025 iThome 鐵人賽

DAY 0
0
自我挑戰組

LeetCode 每日一題挑戰系列 第 2

Day 1:解決 Two Sum 問題(Java 範例)

  • 分享至 

  • xImage
  •  

今天我要分享一個經典的程式題目 —— Two Sum。題目很簡單:
給你一個整數陣列 nums 和一個目標值 target,找出陣列中 兩個數字的索引,使它們相加等於目標值。
每個陣列只會有一個解,而且不能使用同一個元素兩次。

這個題目不僅常出現在程式面試,也非常適合作為練習 HashMap 的應用。

程式碼示範(Java)
import java.util.HashMap;
import java.util.Map;

class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numToIndex = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (numToIndex.containsKey(complement)) {
            return new int[] { numToIndex.get(complement), i };
        }
        numToIndex.put(nums[i], i);
    }
    return new int[]![](http://) {};
}

public static void main(String[] args) {
    Solution solution = new Solution();
    
    int[] result1 = solution.twoSum(new int[] {2,7,11,15}, 9);
    System.out.println(result1[0] + "," + result1[1]); // Output: 0,1

    int[] result2 = solution.twoSum(new int[] {3,2,4}, 6);
    System.out.println(result2[0] + "," + result2[1]); // Output: 1,2

    int[] result3 = solution.twoSum(new int[] {3,3}, 6);
    System.out.println(result3[0] + "," + result3[1]); // Output: 0,1
}

}

解法說明

使用 HashMap 儲存每個數字對應的索引

每次迴圈計算 complement = target - nums[i]

如果 HashMap 裡有 complement,表示找到答案,直接返回兩個索引

否則,將當前數字加入 HashMap,繼續搜尋

這種方法時間複雜度為 O(n),比傳統兩層迴圈的 O(n²) 快很多。

心得小結

這個題目教會我兩件事:

HashMap 很好用:可以快速查找對應值,省去多層迴圈

程式思路很重要:先想「補數」再存索引,比直接兩層迴圈更直觀
undefinedhttps://ithelp.ithome.com.tw/upload/images/20250915/20169537uGxcgByTAS.pnghttps://ithelp.ithome.com.tw/upload/images/20250915/20169537e6XnzUwC9l.pnghttps://ithelp.ithome.com.tw/upload/images/20250915/20169537FA8gZiChsH.png


上一篇
LeetCode 鐵人賽 Day 9 — Regular Expression Matching
下一篇
Day 2 - Longest Substring Without Repeating Characters
系列文
LeetCode 每日一題挑戰9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言