- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumUnsorted.java
More file actions
Latest commit
31 lines (24 loc) · 891 Bytes
/
Copy pathTwoSumUnsorted.java
File metadata and controls
31 lines (24 loc) · 891 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
packagecom.sarvesh.javabasics;
importjava.util.HashMap;
importjava.util.Arrays;
publicclassTwoSumUnsorted {
publicstaticvoidmain(String[] args) {
int[] arr = {7, 11, 2, 15};
inttarget = 9;
int[] result = twoSum(arr, target);
System.out.println("Match found at indexes: " + Arrays.toString(result));
}
publicstaticint[] twoSum(int[] nums, inttarget) {
HashMap<Integer, Integer> num = newHashMap<>();
for (inti = 0; i < nums.length; i++) {
intcurrentNum = nums[i];
intcomplement = target - currentNum;
if (num.containsKey(complement)) {
intcomplementIndex = num.get(complement);
returnnewint[] { complementIndex, i };
}
num.put(currentNum, i);
}
returnnewint[] {};
}
}