Skip to content

Commit 9f29d25

Browse files
committed
update 001
1 parent 5257949 commit 9f29d25

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

note/001/README.md

+38-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,50 @@
1-
# [xxx][title]
1+
# [Two Sum][title]
22

33
## Description
44

5+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
6+
7+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
8+
9+
**Example:**
10+
11+
```
12+
Given nums = [2, 7, 11, 15], target = 9,
13+
14+
Because nums[0] + nums[1] = 2 + 7 = 9,
15+
return [0, 1].
16+
```
517

618
## 思路
719

20+
给定一个数组和一个总数,返回数组中两个数的索引,这两个数的和等于给定的总数。
21+
22+
遍历数组,使用一个 HashMap 记录数组里的数及其索引,如果总数与当前数的差值在 HashMap 里存在相应的记录,就找到了。
823

924
## [完整代码][src]
1025

1126
```java
12-
27+
class Solution {
28+
public int[] twoSum(int[] nums, int target) {
29+
if (nums == null || nums.length < 2) {
30+
return null;
31+
}
32+
33+
Map<Integer, Integer> map = new HashMap<>();
34+
for (int i = 0; i < nums.length; i++) {
35+
if (map.containsKey(target - nums[i])) {
36+
int[] result = new int[2];
37+
result[0] = map.get(target - nums[i]);
38+
result[1] = i;
39+
return result;
40+
}
41+
map.put(nums[i], i);
42+
}
43+
44+
return null;
45+
}
46+
}
1347
```
1448

15-
[title]: https://leetcode.com/problems/xxx
16-
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_xxx/Solution.java
49+
[title]: https://leetcode.com/problems/two-sum
50+
[src]: https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_001/Solution.java

0 commit comments

Comments
 (0)