forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGangBean.java
More file actions
35 lines (31 loc) · 1.06 KB
/
GangBean.java
File metadata and controls
35 lines (31 loc) · 1.06 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
class Solution {
public int[] twoSum(int[] nums, int target) {
/**
1. understanding
- find the indices where the numbers of that index pair sum upto the target number.
- exactly one solution
- use each element only once
- return in any order
2. strategy
- brute force:
- validate for all pair sum
- hashtable:
- assing hashtable variable to save the nums and index
- while iterate over the nums,
- calculate the diff, and check if the diff in the hashtable.
- or save new entry.
3. complexity
- time: O(N)
- space: O(N)
*/
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (map.containsKey(diff)) {
return new int[] {map.get(diff), i};
}
map.put(nums[i], i);
}
return new int[] {};
}
}