Skip to content

Commit 2b465db

Browse files
committed
Merge pull request #1 from Mengman/ycli
Implement twoSum in java
2 parents 407b5ba + dd27b09 commit 2b465db

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

.gitgnore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.class
2+
.pyc
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Source : https://oj.leetcode.com/problems/two-sum/
2+
// Author : ycli
3+
// Date : 2015-05-29
4+
5+
/**********************************************************************************
6+
*
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,
10+
* where index1 must be less than index2. Please note that your returned answers (both index1 and index2)
11+
* are not zero-based.
12+
*
13+
* You may assume that each input would have exactly one solution.
14+
*
15+
* Input: numbers={2, 7, 11, 15}, target=9
16+
* Output: index1=1, index2=2
17+
*
18+
*
19+
**********************************************************************************/
20+
package algorithms_java.twoSum;
21+
22+
import java.lang.Integer;
23+
import java.util.Map;
24+
import java.util.HashMap;
25+
26+
public class Solution {
27+
28+
public int[] twoSum(int[] nums, int target){
29+
int result[] = new int[2];
30+
Map<Integer, Integer> m = new HashMap<>();
31+
for (int i = 0; i < nums.length ; i++) {
32+
int key = target - nums[i];
33+
if (m.containsKey(key)) {
34+
result[0] = m.get(key) + 1;
35+
result[1] = i + 1;
36+
break;
37+
38+
}
39+
else {
40+
m.put(key, i);
41+
}
42+
43+
}
44+
45+
return result;
46+
}
47+
}

0 commit comments

Comments
 (0)