Total Accepted: 188053
Total Submissions: 888224
Difficulty: Medium
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.
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
《编程之美》上的一道原题,如果用暴力枚举的方法,时间复杂度将是n的平方。但是如果借助hash技术可以巧妙的将平方复杂度降级。
我的AC代码
public class TwoSum {
public static void main(String[] args) {
int[] a = { 2, 7, 11, 15 };
System.out.println(twoSum(a, 9));
}
public static int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
int n2;
Integer idx;
Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length);
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length - 1; i++) {
n2 = target - nums[i];
idx = map.get(n2);
if(idx != null && idx > i){
result[0] = i;
result[1] = idx;
break;
}
}
return result;
}
}