Skip to content

Commit 755c462

Browse files
committed
1 parent 6b3b073 commit 755c462

File tree

4 files changed

+69
-4
lines changed

4 files changed

+69
-4
lines changed

README.md

-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1 @@
11
# leetcode
2-
3-
4-
5-
## 前言

pom.xml

+10
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,16 @@
88
<artifactId>leetcode</artifactId>
99
<version>1.0</version>
1010

11+
<dependencies>
12+
<dependency>
13+
<groupId>junit</groupId>
14+
<artifactId>junit</artifactId>
15+
<version>4.13</version>
16+
<scope>test</scope>
17+
</dependency>
18+
19+
</dependencies>
20+
1121
<build>
1222
<plugins>
1323
<plugin>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package name.guolanren._1to100._1to10.p1;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @link https://leetcode.com/problems/two-sum/
8+
* @author guolanren
9+
*/
10+
public class TwoSum {
11+
12+
public int[] twoSum(int[] nums, int target) {
13+
14+
int[] indices = new int[2];
15+
Map<Integer, Integer> numsMap = new HashMap<>(nums.length);
16+
17+
for (int i = 0; i < nums.length; i++) {
18+
int current = nums[i];
19+
int anotherLookFor = target - current;
20+
Integer anotherIndex;
21+
22+
// 如果待查找的数在 map 中有匹配,则表示找到符合要求的 indices
23+
if ((anotherIndex = numsMap.get(anotherLookFor)) != null) {
24+
indices[0] = anotherIndex;
25+
indices[1] = i;
26+
}
27+
28+
numsMap.put(nums[i], i);
29+
}
30+
31+
return indices;
32+
}
33+
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package name.guolanren._1to100._1to10.p1;
2+
3+
import org.junit.Before;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.*;
7+
8+
public class TwoSumTest {
9+
10+
private TwoSum twoSum;
11+
private int[] nums;
12+
private int target;
13+
14+
@Before
15+
public void before() {
16+
twoSum = new TwoSum();
17+
nums = new int[]{2, 7, 11, 15};
18+
target = 9;
19+
}
20+
21+
@Test
22+
public void twoSum() {
23+
assertArrayEquals(new int[]{0, 1}, twoSum.twoSum(nums, target));
24+
}
25+
}

0 commit comments

Comments
 (0)