forked from yuduozhou/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTwoSum.java
More file actions
22 lines (22 loc) · 752 Bytes
/
TwoSum.java
File metadata and controls
22 lines (22 loc) · 752 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
int[] result = new int[2];
for (int i = 0; i < numbers.length; i++){
myMap.put(numbers[i], i);
}
for (int i = 0; i < numbers.length; i++){
if (myMap.containsKey(target - numbers[i])){
int j = myMap.get(target - numbers[i]) +1;
i++;
result[0] = (i < j) ? i : j;
result[1] = (i < j) ? j : i;
return result;
}
}
return result;
}
}