1. Two Sum

題目原文

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解題思路

  1. 先計算每一個數字還差多少才會等於target,相差值暫稱為complement。

  2. 去map裡找是否存在complement,如果發現返回數字的index與complement的index。

  3. 如果沒有發現complement,把數字放入map裡,指向下一個數字,回到步驟2。

程式解答

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        map<int, int> p1;
        map<int, int>::iterator it;
        vector<int> p2;
        
        for (int i = 0; i < nums.size(); i++) 
        {
            int complement = target - nums[i];
            it = p1.find(complement);
            
            if (it != p1.end()) 
            {
                p2.insert(p2.begin() + 0, p1.at(complement));
                p2.insert(p2.begin() + 1, i);
                return p2;
            }
            
            p1.insert(pair<int, int>(nums[i], i));
        }
    }
};

Last updated

Was this helpful?