forked from huxiaoman7/leetcodebook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
38 lines (31 loc) · 803 Bytes
/
Copy pathTwoSum.java
File metadata and controls
38 lines (31 loc) · 803 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package leetcode;
import java.util.HashMap;
/**
* Created by huxiaoman on 2019/2/27 3:01 PM.
* E-mail: charlotte77_hu@sina.com
*/
public class TwoSum {
/**
* time : O(n)
* space : O(n)
* @params: nums
* @params: target
* @return
*/
public int[] twoSum(int[] nums, int target){
int[] result = new int[2];
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++){
if (map.containsKey(target-nums[i])){
result[0] = map.get(target-nums[i]);
result[1] = i;
break;
}
map.put(nums[i],i);
}
return result;
}
}
public static void main(String[] args){
TwoSum([2,7,11,15],9])
}