Skip to content

Commit 82e7549

Browse files
committed
两数之和
1 parent 6b88dad commit 82e7549

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@
197197
- [Subarray Sum](/algorithm/LeetCode/Array/Subarray-Sum.md)
198198
- [Plus One](/algorithm/LeetCode/Array/plus-one.md)
199199
- [Palindrome Number](/algorithm/LeetCode/Array/Palindrome-Number.md)
200+
- [Two Sum](/algorithm/LeetCode/Array/Two-Sum.md)
200201
- [String](/algorithm/LeetCode/String.md)
201202
- [Restore IP Addresses](/algorithm/LeetCode/String/ip.md)
202203

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
## 一、题目
2+
3+
>Given an array of integers, return indices of the two numbers such that they add up to a specific target.
4+
>
5+
>You may assume that each input would have exactly one solution.
6+
>
7+
>Example:
8+
>
9+
>Given nums = [2, 7, 11, 15], target = 9,
10+
>Because nums[0] + nums[1] = 2 + 7 = 9,
11+
>return [0, 1].
12+
13+
给定一个整型数组,找出能相加起来等于一个特定目标数字的两个数。
14+
15+
## 二、解题思路
16+
17+
用hashmap,hashmap是内部存储方式为哈希表的map结构。遍历数组,其中key存放目标值减去当前值,value存放对应索引。如果在遍历过程中发现map中存在与当前值相等的key,则返回结果。
18+
19+
## 三、解题代码
20+
21+
```java
22+
public class Solution {
23+
/*
24+
* @param numbers : An array of Integer
25+
* @param target : target = numbers[index1] + numbers[index2]
26+
* @return : [index1 + 1, index2 + 1] (index1 < index2)
27+
numbers=[2, 7, 11, 15], target=9
28+
return [1, 2]
29+
*/
30+
public int[] twoSum(int[] numbers, int target) {
31+
HashMap<Integer,Integer> map = new HashMap<>();
32+
33+
for (int i = 0; i < numbers.length; i++) {
34+
if (map.get(numbers[i]) != null) {
35+
int[] result = {map.get(numbers[i]) + 1, i + 1};
36+
return result;
37+
}
38+
map.put(target - numbers[i], i);
39+
}
40+
41+
int[] result = {};
42+
return result;
43+
}
44+
}
45+
```
46+

0 commit comments

Comments
 (0)