> For the complete documentation index, see [llms.txt](https://jimmy-walker.gitbook.io/leetcode-training/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmy-walker.gitbook.io/leetcode-training/array/two-sum.md).

# Two Sum

## Question

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

You may assume that each input would have exactly one solution.

## Example:

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

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

## Hint

The return format had been changed to zero-based indices. Please read the above updated description carefully.

## Answer

### solution：

```python
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup = {}
        for i, num in enumerate(nums):
            if target - num in lookup: #思想为对每一个元素a去查是否有另一个使其满足条件的数b存在，那么就需要将每一个元素存到另一个数据结构中去以作为判断（因为如果不存新的数据结构的话，直接遍历会使得序号访问变复杂，比如说空出当前值a，所以索性就新建一个数据结构保存已经检查完的数），从而达到依次判断的效果。
            #注意判断字典中值的方法，直接if a in dict:即可
                return [lookup[target - num], i]
            lookup[num] = i
        return []
```

## Knowledge：

1. enumerate() 函数用于遍历序列中的元素的下标以及元素，这一类问题叫**下标元素类**。

   其常用形式for i, num in enumerate(nums):
2. 下标元素类的问题常常需要用到，单循环加上字典辅助：

   ```
    if num not in lookup:
        lookup[num] = i
   ```
3. 注意判断字典中值的方法，直接if a in dict:即可


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://jimmy-walker.gitbook.io/leetcode-training/array/two-sum.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
