-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwoSum.java
More file actions
27 lines (23 loc) · 747 Bytes
/
twoSum.java
File metadata and controls
27 lines (23 loc) · 747 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
import java.util.Arrays;
import java.util.HashMap;
public class twoSum {
public static void main(String[] args) {
int[] nums = {3, 5, 4, 6};
int target = 7;
System.out.println(Arrays.toString(twoSumFunction(nums, target)));
}
public static int[] twoSumFunction(int[] nums, int target){
HashMap<Integer, Integer> map = new HashMap<>();
int[] result = new int[2];
for(int i = 0; i < nums.length; i++){
int difference = target - nums[i];
if(map.containsKey(difference)){
result[0] = map.get(difference);
result[1] = i;
}else{
map.put(nums[i], i);
}
}
return result;
}
}