-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSumFind.java
More file actions
76 lines (60 loc) · 1.9 KB
/
Copy pathTwoSumFind.java
File metadata and controls
76 lines (60 loc) · 1.9 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
68
69
70
71
72
73
74
75
76
package LinkedInQuestions;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ranjan on 7/24/16.
* Design and implement a TwoSum class. It should support the following operations: add and find.
add(input) – Add the number input to an internal data structure.
find(value) – Find if there exists any pair of numbers which sum is equal to the value.
*/
public class TwoSumFind {
private Map<Integer, Integer> table = new HashMap<>();
HashMap<Integer, Integer> hm = new HashMap<>();
public void add(int input){
int count = table.containsKey(input)?table.get(input):0;
table.put(input,count+1);
}
public boolean find(int val){
for(Map.Entry<Integer,Integer> entry: table.entrySet()){
int num = entry.getKey();
int y = val - num;
if(y==num){
if(entry.getValue()>=2){
return true;
} else if(table.containsKey(y)){
return true;
}
}
}
return false;
}
/*
Second Solution working
*/
public void two_sum_prob_sum(int arr[]) {
for (int i = 0; i < arr.length; i++) {
hm.put(arr[i], arr[i]);
}
}
public void two_sum_prob_find(int arr[], int sum){
for(int i = 0; i<arr .length;i++){
int lookFor = sum-arr [i];
boolean hasValue = hm.containsValue(lookFor);
if(hasValue){
System.out.println("Found: "+arr[i]+"+"+ lookFor + "="+sum);
}
}
}
public static void main(String[] args){
TwoSumFind tsw = new TwoSumFind();
tsw.add(11);
tsw.add(3);
tsw.add(5);
tsw.add(9);
System.out.println(tsw.find(20));
int[] arr = {1,3,5,9};
int sum = 8;
tsw.two_sum_prob_sum(arr);
tsw.two_sum_prob_find(arr,sum);;
}
}