# 07. 두 수의 합(leetcode: 1)

[**문제링크**](https://leetcode.com/problems/two-sum/)

{% embed url="<https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Map>" %}
Map과 Object는 다르다
{% endembed %}

## 문제 분석

인자 nums 에서 두 값을 더 했을 때 target이 되는 요소를 찾은 뒤 해당 요소의 인덱스를 리턴하면 된다. 문제 자체는 어렵지 않다.

이런 문제에서 정말 유용하게 사용될 수 있는게 **우리가 찾길 원하는 값을 MAP의 키 값으로 넣는것**.

## 해결

```javascript
var twoSum = function(nums, target) {
    let diffMap = new Map();
    for (let i = 0; i < nums.length; i++) {
        if (diffMap.has(target - nums[i])) {
            return [diffMap.get(target - nums[i]), i]
        }
        diffMap.set(nums[i], i);
    }
};
```

여기서 핵심은 반복을 돌면서

1. Map의 키로 원하는 값이 있는지를 찾고
2. 있으면 map 에 존재하는 키의 인덱스와 현재 반복문으 인덱스를 리턴
3. 없으면 Map 에 현재 요소를 추가


---

# 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://simian114.gitbook.io/blog/undefined/undefined-1/07.-leetcode-1.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.
