-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumUnsorted.java
More file actions
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
package com.sarvesh.javabasics;
import java.util.HashMap;
import java.util.Arrays;
public class TwoSumUnsorted {
public static void main(String[] args) {
int[] arr = {7, 11, 2, 15};
int target = 9;
int[] result = twoSum(arr, target);
System.out.println("Match found at indexes: " + Arrays.toString(result));
}
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> num = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int currentNum = nums[i];
int complement = target - currentNum;
if (num.containsKey(complement)) {
int complementIndex = num.get(complement);
return new int[] { complementIndex, i };
}
num.put(currentNum, i);
}
return new int[] {};
}
}