-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.java
More file actions
28 lines (22 loc) · 741 Bytes
/
twoSum.java
File metadata and controls
28 lines (22 loc) · 741 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
import java.util.*;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map <Integer, Integer> seen = new HashMap<>();
for(int i = 0; i < nums.length; i++){
int comp = target - nums[i];
if(seen.containsKey(comp)){
return new int[] {seen.get(comp), i};
} else {
seen.put(nums[i], i);
}
}
throw new IllegalArgumentException("No Match");
}
public static void main(String[] args){
Solution solution = new Solution();
int[] nums = {2,7,11,15};
int target = 9;
int[] result = solution.twoSum(nums, target);
System.out.println(Arrays.toString(result));
}
}