Skip to content

Commit 17a3842

Browse files
authored
Create twosum.java
1 parent 86f7d11 commit 17a3842

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Leetcode/Hashmap/twosum.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.*;
2+
3+
public class Solution {
4+
public int[] twoSum(int[] nums, int target) {
5+
6+
HashMap<String, Integer> numbers = new HashMap<String, Integer>();
7+
8+
for(int i=0; i<nums.length;i++) {
9+
numbers.put(Integer.toString(nums[i]),i);
10+
}
11+
12+
for(int i=0, place=i; i<nums.length;i++) {
13+
14+
int distance = target - nums[i];
15+
16+
if (numbers.containsKey(Integer.toString(distance))) {
17+
place = numbers.get(Integer.toString(distance));
18+
if (i!=place){
19+
return new int[]{i,place};
20+
}
21+
}
22+
}
23+
24+
return new int[]{0,0};
25+
}
26+
}

0 commit comments

Comments
 (0)