forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
41 lines (33 loc) · 855 Bytes
/
TwoSum.java
File metadata and controls
41 lines (33 loc) · 855 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
32
33
34
35
36
37
38
39
40
41
package Hashing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Author - archit.s
* Date - 28/10/18
* Time - 3:10 PM
*/
public class TwoSum {
public ArrayList<Integer> twoSum(final List<Integer> A, int B) {
int index1 = -1;
int index2 = -1;
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<A.size();i++){
if(map.containsKey(A.get(i))){
index1 = map.get(A.get(i));
index2 = i;
break;
}
else if(!map.containsKey(B-A.get(i))){
map.put(B-A.get(i), i);
}
}
ArrayList<Integer> r = new ArrayList<>();
if(index1!=-1){
r.add(index1+1);
r.add(index2+1);
}
return r;
}
}