forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSol35229.java
More file actions
31 lines (27 loc) · 909 Bytes
/
Sol35229.java
File metadata and controls
31 lines (27 loc) · 909 Bytes
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
import java.util.HashMap;
import java.util.Map;
public class Sol35229 {
public int[] bruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[i]+nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[] {};
}
public int[] hashTable(int[] nums, int target) {
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
hashMap.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (hashMap.containsKey(complement) && hashMap.get(complement) != i) {
return new int[]{i, hashMap.get(complement)};
}
}
return new int[] {};
}
}