-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.java
44 lines (40 loc) · 1.14 KB
/
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
39
40
41
42
43
44
package _001;
import java.util.Arrays;
import java.util.HashMap;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2017/04/21
* desc :
* </pre>
*/
public class Solution {
// public int[] twoSum(int[] nums, int target) {
// for (int i = 0; i < nums.length; ++i) {
// for (int j = i + 1; j < nums.length; ++j) {
// if (nums[i] + nums[j] == target) {
// return new int[]{i, j};
// }
// }
// }
// return null;
// }
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; ++i) {
if (map.containsKey(nums[i])) {
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
return null;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = new int[]{2, 7, 11, 15};
int target = 9;
System.out.println(Arrays.toString(solution.twoSum(nums, target)));
}
}