Skip to content

Commit 0984ef6

Browse files
committed
hasmap
1 parent c7a2647 commit 0984ef6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

sequence/TwoSum.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package Algorithms.sequence;
2+
3+
import java.util.HashMap;
4+
5+
/*
6+
* Two Sum Total Accepted: 36938 Total Submissions: 200732 My Submissions Question Solution
7+
Given an array of integers, find two numbers such that they add up to a specific target number.
8+
9+
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
10+
11+
You may assume that each input would have exactly one solution.
12+
13+
Input: numbers={2, 7, 11, 15}, target=9
14+
Output: index1=1, index2=2
15+
* */
16+
17+
public class TwoSum {
18+
public int[] twoSum(int[] numbers, int target) {
19+
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
20+
int[] ret = new int[2];
21+
22+
for (int i = 0; i < numbers.length; i++) {
23+
if (map.containsKey(target - numbers[i])) {
24+
25+
// As the index is not ZERO based, we should add one to the result.
26+
ret[0] = map.get(target - numbers[i]) + 1;
27+
ret[1] = i + 1;
28+
return ret;
29+
}
30+
map.put(numbers[i], i);
31+
}
32+
33+
return ret;
34+
}
35+
}

0 commit comments

Comments
 (0)