-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
36 lines (33 loc) · 1 KB
/
Copy pathTwoSum.java
File metadata and controls
36 lines (33 loc) · 1 KB
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
package com.al.TwoSum;
import java.util.HashMap;
/**
* lc #1 two sum
*/
public class TwoSum {
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums.length < 2) return new int[]{};
HashMap<Integer,Integer> hs = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
hs.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int value = target - nums[i];
if (hs.containsKey(value) && hs.get(value)!=i) {
res[0] = i;
res[1] = hs.get(value);
return res;
}
}
return res;
}
}
public static void main(String[] args) {
Solution sl = new TwoSum().new Solution();
int[] test = sl.twoSum(new int[]{2,7,11,15}, 9);
for (int i = 0; i < test.length; i++) {
System.out.println(test[i]);
}
}
}