-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0056. Two Sum
More file actions
24 lines (24 loc) · 823 Bytes
/
0056. Two Sum
File metadata and controls
24 lines (24 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
/**
* @param numbers: An array of Integer
* @param target: target = numbers[index1] + numbers[index2]
* @return: [index1, index2] (index1 < index2)
*/
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i<numbers.length; i++){
map.put(numbers[i], i);
}
int[] result = new int[2];
for(int i = 0; i<numbers.length; i++){
if(map.get(target-numbers[i]) != null){
int temp = map.get(target-numbers[i]);
result[0] = Math.min(temp, i);
result[1] = Math.max(temp, i);
return result;
}
}
result[0] = result[1] = -1;
return result;
}
}