-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathTwo Sum O(n) 3 approach.java
67 lines (53 loc) · 1.76 KB
/
Two Sum O(n) 3 approach.java
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
// 1.
// Runtime: 2 ms, faster than 93.55%
// Time Complexity: O(N)
// Space Complexity: O(N)
class Solution {
public int[] twoSum(int[] nums, int target) {
int res[] = new int[2];
Map <Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target - nums[i])){
res[0] = map.get(target-nums[i]);
res[1] = i;
return res;
}
map.put(nums[i],i);
}
return res;
}
}
//2
// Runtime: 3 ms, faster than 89.79%
class Solution { // in this not required to do again and again check line by.
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++){
int curr = nums[i];
int required = target - curr;
if(map.containsKey(required)){
int reqIdx = map.get(required);
return new int[] {i,reqIdx};
}else{
map.put(curr,i);
}
}
return null;
}
}
//3
// Runtime: 4 ms, faster than 73.34%
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++){
Integer required = (Integer) (target - nums[i]);
if(map.containsKey(required)){
int ans[] = {map.get(required),i};
return ans;
}
map.put(nums[i],i); // value and index
}
return null;
}
}