1.Two Sum

Posted by Csming on 2017-04-25

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.


题解与理解

  • 题意大致是:给定一个数组,和一个目标数字target;找出数组中和为目标数字target的两个数

解题用了一个HashMap;key为该数字target-nums[i],value为nums[i];

对数组进行遍历,如果map中不存在与其相等的key,则将该数字存入map;

当遍历的数字发现map中存在与其对应的key时,则说明当前遍历数字与前面遍历过的某数字相加为target;
此时获取map中的该数字,存储到result中,并return;

解题源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer , Integer > map = new HashMap<Integer , Integer>();
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;
}
map.put(nums[i], i);
}

return result;
}
}