Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1. Two Sum

Rain Hu

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:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. HashMap

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int,int> map;         // {值, 索引}
    int i;                              // 將 i 宣告在 for-loop 外
    for (i = 0; i < nums.size(); i++) {
        if (map.find(target - nums[i]) != map.end()) 
            break;                      // 若找到答案,則退出迴圈
        map[nums[i]] = i;               // 若沒有符合的答案,將值加入 HashMap
    }
    return {map[target-nums[i]], i};    // 注意加入 HashMap 的索引值會比當下的 i 值還小
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1652. Defuse the Bomb
Next
[LeetCode] 1423. Maximum Points You Can Obtain from Cards