-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainsPairWithSum.java
More file actions
67 lines (54 loc) · 1.4 KB
/
ContainsPairWithSum.java
File metadata and controls
67 lines (54 loc) · 1.4 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Daily Coding Problem
* Got O(n) solution in 30 minutes with 2 passes
* see below for N solution in one pass
**/
import java.util.*;
class ContainsPairWithSum{
public static void main(String[] args){
int[] arr = {10,3,5,7};
int val = 17;
System.out.println(containsPairWithSum(arr,val));
}
public static boolean containsPairWithSum(int[] arr, int num){
if(arr.length < 2){
return false;
}
HashMap<Integer,Integer> table = new HashMap<>();
for(int val : arr){
if(table.containsKey(val)){
table.put(val,table.get(val)+1);
}
else{
table.put(val,1);
}
}
for(int val : arr){
int curr = num - val;
if(num < 1 && curr != 0){
continue;
}
table.put(val,table.get(val)-1);
if(table.containsKey(curr) && table.get(curr) > 0){
return true;
}
table.put(val,table.get(val)+1);
}
return false;
}
}
/**
public static boolean containsPairWithSum(int[] a, int x) {
Arrays.sort(a);
for (int i = 0, j = a.length - 1; i < j;) {
int sum = a[i] + a[j];
if (sum < x)
i++;
else if (sum > x)
j--;
else
return true;
}
return false;
}
*/