###### Two Sum

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

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

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] temp=new int[2];
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
temp[0]=i+1;
temp[1]=j+1;
}
}
}
return temp;
}
}

public class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //记录值和index
int[] ret = new int[2]; //辅助数组
for(int i=0; i<nums.length; i++){
if(map.get(target-nums[i]) != null){  //找到值对应的index
ret[0] = map.get(target-nums[i]) + 1;
ret[1] = i+1;
}else
map.put(nums[i], i);//没有找到则记录
}
return ret;
}
}

#### Two Sum -- LeetCode

2014-02-22 23:11:50

#### leetcode－1. Two Sum－简单的算法题，面试见到了吗？

2016-09-17 12:11:51

#### 1. Two Sum（重要！）

2016-07-09 16:21:27

#### 1. Two Sum [easy] (Python)

2016-07-26 20:19:37

#### LeetCode || Two Sum

2014-04-09 23:11:47

#### 【LeetCode】LeetCode——第1题：Two Sum

2016-01-04 17:01:58

#### 算法系列--Two Sum

2015-09-13 23:34:12

#### LeetCode 第 371 题 （Sum of Two Integers）

2016-07-01 19:56:30

#### 371. Sum of Two Integers [easy] (Python)

2016-07-26 12:08:46

#### 167. Two Sum II - Input array is sorted [medium] (Python)

2016-08-31 19:33:40

Two Sum