-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
36 lines (31 loc) · 849 Bytes
/
Copy pathTwoSum.java
File metadata and controls
36 lines (31 loc) · 849 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
31
32
33
34
35
36
package solutions;
import leet.LeetIO;
import java.util.HashMap;
import java.util.Map;
/**
* Example LeetCode solution showing the LeetIO pattern.
*
* Run this class and paste two lines into the run console:
* [2,7,11,15]
* 9
*
* Expected output:
* [0,1]
*/
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[]{j, i};
seen.put(nums[i], i);
}
return new int[0];
}
public static void main(String[] args) {
LeetIO io = new LeetIO();
int[] nums = io.nextIntArray();
int target = io.nextInt();
io.println(new TwoSum().twoSum(nums, target));
}
}