Skip to content

Commit 50dcab4

Browse files
committed
feat: solve two sum
1 parent 1654d1d commit 50dcab4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

two-sum/GangBean.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public int[] twoSum(int[] nums, int target) {
3+
/**
4+
1. understanding
5+
- find the indices where the numbers of that index pair sum upto the target number.
6+
- exactly one solution
7+
- use each element only once
8+
- return in any order
9+
2. strategy
10+
- brute force:
11+
- validate for all pair sum
12+
- hashtable:
13+
- assing hashtable variable to save the nums and index
14+
- while iterate over the nums,
15+
- calculate the diff, and check if the diff in the hashtable.
16+
- or save new entry.
17+
3. complexity
18+
- time: O(N)
19+
- space: O(N)
20+
*/
21+
22+
Map<Integer, Integer> map = new HashMap<>();
23+
24+
for (int i = 0; i < nums.length; i++) {
25+
int diff = target - nums[i];
26+
if (map.containsKey(diff)) {
27+
return new int[] {map.get(diff), i};
28+
}
29+
map.put(nums[i], i);
30+
}
31+
32+
return new int[] {};
33+
}
34+
}
35+

0 commit comments

Comments
 (0)