-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSolution1.java
More file actions
34 lines (25 loc) · 985 Bytes
/
Solution1.java
File metadata and controls
34 lines (25 loc) · 985 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
31
32
33
34
package hash_table_problem;
import java.util.HashMap;
/**
* Two Sum 系列——1:
* 1、索引从0开始计算还是从1开始计算?
* 2、没有解怎么办?
* 3、有多个解怎么办?保证有唯一解。
* 4、暴力解法 O(n^2)
* 5、排序后,使用双索引对撞:O(nlogn) + O(n) = O(nlogn)
* 6、查找表(map),将所有元素放入查找表,之后对每一个元素 a,查找 target - a 是否存在。O(n)
*/
public class Solution1 {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> record = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (record.containsKey(complement)) {
int[] res = {record.get(complement), i};
return res;
}
record.put(nums[i], i);
}
throw new IllegalArgumentException("no this array exist!");
}
}