Skip to content

Commit 20fe4a4

Browse files
committed
Added
'Two Sum'
1 parent cb92c1d commit 20fe4a4

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Two Sum.java

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// https://leetcode.com/problems/two-sum/
2+
3+
class Solution {
4+
public int[] twoSum1(int[] nums, int target) {
5+
6+
/* BRUTE FORCE */
7+
8+
// Create a return list
9+
int[] ans = new int[2];
10+
11+
// Iterate nums
12+
for (int i = 0; i < nums.length; i++) {
13+
for (int j = i + 1; j < nums.length; j++) {
14+
if (nums[i] + nums[j] == target) {
15+
ans[0] = i;
16+
ans[1] = j;
17+
18+
return ans;
19+
}
20+
}
21+
}
22+
23+
return ans;
24+
}
25+
26+
public int[] twoSum(int[] nums, int target) {
27+
28+
/* HASH MAP APPROACH
29+
*
30+
* Time Complexity: O(n) = n is the length of nums.
31+
*
32+
* Space Complexity: O(n) = n is map size.
33+
*/
34+
35+
// Create a hash map
36+
Map<Integer, Integer> map = new HashMap<>();
37+
38+
// Put all the elements to hash map
39+
for (int i = 0; i < nums.length; i++) {
40+
map.put(nums[i], i);
41+
}
42+
43+
// Find the complement
44+
// I.e., nums[i] + X = target. X is the complement.
45+
for (int i = 0; i < nums.length; i++) {
46+
int complement = target - nums[i];
47+
48+
// If complement exist in map and it isn't itself, then return list
49+
if (map.containsKey(complement) && map.get(complement) != i) {
50+
return new int[] {map.get(complement), i};
51+
}
52+
}
53+
54+
return null;
55+
}
56+
}

0 commit comments

Comments
 (0)