forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.java
43 lines (33 loc) · 1.1 KB
/
Solution2.java
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
39
40
41
42
43
/// Source : https://leetcode.com/problems/two-sum/description/
/// Author : liuyubobobo
/// Time : 2017-11-15
/// Updated: 2018-12-28
import java.util.HashMap;
/// Two-Pass Hash Table
/// Time Complexity: O(n)
/// Space Complexity: O(n)
public class Solution2 {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length ; i ++)
record.put(nums[i], i);
for(int i = 0 ; i < nums.length; i ++){
Integer index = record.get(target - nums[i]);
if(index != null && index != i){
int[] res = {i, index};
return res;
}
}
throw new IllegalStateException("the input has no solution");
}
private static void printArr(int[] nums){
for(int num: nums)
System.out.print(num + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {0, 4, 3, 0};
int target = 0;
printArr((new Solution2()).twoSum(nums, target));
}
}