Skip to content

Commit de5d365

Browse files
committed
Number 1
0 parents  commit de5d365

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

1. Two Sum.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class TwoSum {
2+
3+
/**
4+
* 1. Two Sum
5+
6+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
7+
8+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
9+
10+
Given nums = [2, 7, 11, 15], target = 9,
11+
12+
Because nums[0] + nums[1] = 2 + 7 = 9,
13+
14+
return [0, 1].
15+
16+
time : O(n)
17+
space : O(n)
18+
* @param nums
19+
* @param target
20+
* @return
21+
*/
22+
23+
public static int[] twoSum(int[] nums, int target) {
24+
25+
if (nums == null || nums.length < 2) {
26+
return new int[]{-1, -1};
27+
}
28+
29+
int[] res = new int[]{-1, -1};
30+
HashMap<Integer, Integer> map = new HashMap<>();
31+
for (int i = 0; i < nums.length; i++) {
32+
if (map.containsKey(target - nums[i])) {
33+
res[0] = map.get(target - nums[i]);
34+
res[1] = i;
35+
break;
36+
}
37+
map.put(nums[i], i);
38+
}
39+
40+
return res;
41+
}
42+
}

0 commit comments

Comments
 (0)