forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
31 lines (27 loc) · 785 Bytes
/
TwoSum.java
File metadata and controls
31 lines (27 loc) · 785 Bytes
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
package com.examplehub.leetcode.easy;
import java.util.HashMap;
import java.util.Map;
/** https://leetcode.com/problems/two-sum/ */
public class TwoSum {
public static int[] solution1(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; ++i) {
for (int j = i + 1; j < nums.length; ++j) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return null;
}
public static int[] solution2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] {map.get(complement), i};
}
map.put(nums[i], i);
}
return null;
}
}