Skip to content

Commit 65b6970

Browse files
Update TwoSum.java
1 parent 84464f9 commit 65b6970

1 file changed

Lines changed: 24 additions & 19 deletions

File tree

Arrays/TwoSum.java

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,32 @@
1-
import java.util.Scanner;
2-
31
class TwoSum {
4-
5-
public static int[] checkTwoSum(int[] nums, int target) {
6-
for(int i=0; i <nums.length; i++){
7-
for(int j= i+1; j<nums.length; j++){
8-
if(nums[i]+nums[j]==target){
9-
int[] arr = {nums[i],nums[j]};
10-
return arr;
2+
public int[] twoSumBrute(int[] nums, int target) { // brute-force O(n^2) time
3+
int n = nums.length;
4+
int[] result = new int[2];
5+
for(int i = 0; i<n; i++){
6+
for(int j = 0; j<n; j++){
7+
if((nums[i]+nums[j]) == target && (i!=j)){
8+
result[0] = i;
9+
result[1] = j;
10+
return result;
1111
}
1212
}
1313
}
14-
throw new IllegalArgumentException("No two-sum solution");
1514
}
1615

17-
public static void main(String[] args){
18-
Scanner input = new Scanner(System.in);
19-
int target = input.nextInt();
20-
int n = input.nextInt();
21-
int[] nums = new int[n];
22-
for(int i=0; i<n; i++){
23-
nums[i] = input.nextInt();
16+
public int[] twoSumHash(int[] nums, int target) { // 1-Hash approach O(n) time
17+
Map<Integer, Integer> map = new HashMap<>();
18+
int[] result = new int[2];
19+
20+
for(int i = 0; i<nums.length; i++){
21+
int complement = target-nums[i];
22+
if(map.containsKey(complement) && map.get(complement)!= i){
23+
result[0] = i;
24+
result[1] = map.get(complement);
25+
return result;
26+
}
27+
map.put(nums[i], i);
2428
}
25-
checkTwoSum(nums, target);
26-
}
29+
}
30+
31+
return result;
2732
}

0 commit comments

Comments
 (0)