-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
30 lines (25 loc) · 814 Bytes
/
TwoSum.java
File metadata and controls
30 lines (25 loc) · 814 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
25
26
27
28
29
30
import java.util.HashMap;
import java.util.Map;
/**
* @author Lillard
*/
public class TwoSum {
public static class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> num2Index = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
final int targetNum = target - nums[i];
if (num2Index.get(targetNum) != null) {
return new int[]{num2Index.get(targetNum), i};
}
num2Index.put(nums[i], i);
}
return null;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] res = solution.twoSum(new int[]{2, 7, 11, 15}, 9);
System.out.println(res[0] + " " + res[1]);
}
}