3sum

3Sum

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Solution1

Brute Force

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int[] twoSum(int[] nums, int target) {
if (nums.length == 0) {
return null;
}

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;
}

Solution2

HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int[] twoSum(int[] nums, int target) {
if (nums.length == 0) {
return null;
}

Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int current = nums[i];
int expect = target - current;
if (map.containsKey(expect)) {
return new int[]{i, map.get(expect)};
}
map.put(current, i);
}
return null;
}