-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSolution.java
More file actions
39 lines (33 loc) · 1.14 KB
/
Solution.java
File metadata and controls
39 lines (33 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package TwoSum;
import java.util.HashMap;
import java.util.Map;
/**
Given an array of integers, find two numbers such that they add up to a specific target number.
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. Please note that your returned answers (both index1 and index2) are not zero-based.
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 {
/**
* Hash, O(n)
* @param numbers
* @param target
* @return
*/
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<numbers.length; i++) {
map.put(numbers[i], i);
}
for(int i=0; i<numbers.length; i++) {
int remain = target-numbers[i];
if(map.containsKey(remain)&&i!=map.get(remain)) {
int[] result = {i+1, map.get(remain)+1};
return result;
}
}
int[] result = {-1, -1};
return result;
}
}