forked from liuyubobobo/Play-with-Algorithm-Interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
38 lines (29 loc) · 985 Bytes
/
Solution.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
import java.util.HashMap;
// 1. Two Sum
// https://leetcode.com/problems/two-sum/description/
// 时间复杂度:O(n)
// 空间复杂度:O(n)
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
for(int i = 0 ; i < nums.length; i ++){
int complement = target - nums[i];
if(record.containsKey(complement)){
int[] res = {i, record.get(complement)};
return res;
}
record.put(nums[i], i);
}
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 Solution()).twoSum(nums, target));
}
}