-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo sum
More file actions
72 lines (48 loc) · 1.49 KB
/
Two sum
File metadata and controls
72 lines (48 loc) · 1.49 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
Using Arrays and two pointers.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index= new int[2];
for(int i=0;i<nums.length;++i){
for(int x=i+1;x<nums.length;++x){
if(target==nums[i] + nums[x]){
index[0]=i;
index[1]=x;
return index;
}
}
}
return index ;
}
}
Using Brute force
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
for(int x=i+1;x<nums.length;x++){
int complement=target-nums[i];
if(complement==nums[x]){
return new int [] {i,x};
}
}
}
throw new IllegalArgumentException("No match found");
}
}
Using HasMap.
class Solution {
public int[] twoSum(int[] nums, int target) {
// Create a HashMap
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
// Get the complement using the target value
int complement = target - nums[i];
// Search the hashmap for complement, if found, we got our pair
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
// Put the element in hashmap for subsequent searches.
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}