LeetCode-Two Sum

Posted by mapoto4 on 2017-07-04

题目

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.

解题思路

  1. 把target-nums[i]作为key值放入hashmap
  2. 遍历数组检查hashmap中是否已经存在相加等一target值
  3. 存在取出
  4. 不存在将自己存入hashmap继续遍历

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
int []result=new int[]{0,1};

for(int i=0;i<nums.length;i++)
{
if(map.containsKey(target-nums[i]))
{
result[1] = i;
result[0] = map.get(target-nums[i]);
return result;
}
else
{
map.put(nums[i],i);
}
}
return result;
}