# LeetCode1.两数之和

### 解题思路：

#### 2.HashMap两层循环

[3, 3] 6 结果应为[0,0],实际为[1,1]

### 代码展示：

Java版：

import java.util.HashMap;

/*
* @lc app=leetcode.cn id=1 lang=java
*
* [1] 两数之和
*/
class Solution {

//HashMap一次循环
public int[] twoSum(int[] nums, int target) {
HashMap map = new HashMap();

for(int j = 0; j < nums.length; j++){
int sub = target - nums[j];
if(map.containsKey(sub)){
return new int[]{map.get(sub), j};
}
map.put(nums[j], j);
}
return new int[2];
}

//HashMap两次循环
public int[] twoSum1(int[] nums, int target) {
HashMap map = new HashMap();

for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}

for(int j = 0; j < nums.length; j++){
int sub = target - nums[j];
if(map.containsKey(sub) && sub != nums[j]){
return new int[]{map.get(sub), j};
}
}
return new int[2];
}

//暴力法
public int[] twoSum2(int[] nums, int target){
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return new int[2];
}
}

Go版：

package leetcode

// 暴力法
func twoSum(nums []int, target int) []int {
result := make([]int, 2)
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
result[0] = i
result[1] = j
return result
}
}
}
return result
}

// HashMap一次循环
func twoSum2(nums []int, target int) []int {
result := make([]int, 2)
m := make(map[int]int)

for j := 0; j < len(nums); j++ {
sub := target - nums[j]
v, ok := m[sub]
if ok {
result[0] = v
result[1] = j
return result
}
m[nums[j]] = j
}
return result
}

// HashMap两次循环，有缺陷
func twoSum3(nums []int, target int) []int {
result := make([]int, 2)
m := make(map[int]int)

for i := 0; i < len(nums); i++ {
m[nums[i]] = i
}

for j := 0; j < len(nums); j++ {
sub := target - nums[j]
v, ok := m[sub]
if ok && v != nums[j] {
result[0] = v
result[1] = j
return result
}
}
return result
}