> For the complete documentation index, see [llms.txt](https://blog.yushunchen.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blog.yushunchen.com/algo/hash-table/two-sum.md).

# Two Sum

{% embed url="<https://leetcode.com/problems/two-sum/>" %}

{% embed url="<https://www.lintcode.com/problem/56/>" %}

## Solution 1 (Go)

```go
func twoSum(nums []int, target int) []int {
    var indices []int
    for i := 0; i < len(nums)-1; i++ {
        for j := i+1; j < len(nums) ; j++ {
            if nums[i] + nums[j] == target {
                indices = append(indices, i, j)
            }
        }
    }
    return indices
}
```

## Solution 2 (Go)

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

## Solution 3 (Java)

```java
public class Solution {
    /**
     * @param numbers: An array of Integer
     * @param target: target = numbers[index1] + numbers[index2]
     * @return: [index1, index2] (index1 < index2)
     */
    public int[] twoSum(int[] numbers, int target) {
        // <number, its index>
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            int j = target - numbers[i];
            if (map.containsKey(j)) {
                return new int[]{map.get(j), i};
            }
            map.put(numbers[i], i);
        }
        return null;
    }
}
```


---

# 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:

```
GET https://blog.yushunchen.com/algo/hash-table/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.
