Question
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
**UPDATE (2016/2/13):
**The return format had been changed to zero-based indices. Please read the above updated description carefully.
Solutions
渣渣表示只会用for循环,就不贴出O(n^2)的弱逼算法了。
去讨论区学习了下,大大们都用的HashMap,我去,HashMap这么高端的东西我长这么大一次都没用过啊!看看了思路,我觉得我是不是要转职了,没法混啊!
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = null;
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) {
map.put(target - nums[i], i);
} else {
int index = map.get(nums[i]);
result = new int[]{index, i};
break;
}
}
return result;
}
}
TO DO
- 教练!我要学HashMap!