# 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].
```

## 解題思路

{% hint style="info" %}

1. 先計算每一個數字還差多少才會等於target，相差值暫稱為complement。
2. 去map裡找是否存在complement，如果發現返回數字的index與complement的index。
3. 如果沒有發現complement，把數字放入map裡，指向下一個數字，回到步驟2。
   {% endhint %}

## 程式解答

```cpp
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));
        }
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://stanley7342.gitbook.io/programming/leetcode/1.-two-sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
