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

# 1. Two Sum

## LeetCode [1. Two Sum](https://leetcode-cn.com/problems/two-sum/)

### Description

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

### Tags

Hash Table, Array

### Solution

使用哈希表记录数字到下标的映射。遍历数组并检查`target-num`是否在哈希表内，如果在则返回当前元素下标和哈希表查出的元素下标构成的元组，否则将当前数字和下标存入哈希表。

Use a hash table to record each element's value and its index. Iterate the array and look up the table if `target-num` is already exists. If it exists, we have found a solution, which is a tuple composed of the index from the table and the current element's index, and return immediately.

### Complexity

* Time complexity: $$O(n)$$
* Space complexity: $$O(n)$$

### Code

```go
func twoSum(nums []int, target int) []int {
	m := map[int]int{} // num:index
	for i, num := range nums {
		if j, ok := m[target-num]; ok {
			return []int{i, j}
		}
		m[num] = i
	}
	return nil
}
```
