k sum in leetcode

2 Sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i + 1;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i], i + 1);
}
return result;
}
}

3 Sum

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
public class {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for(int i = 0; i<nums.length-2;i++){
if (i == 0 || (i > 0 && nums[i] != nums[i-1])) {
int left = i + 1;
int right = nums.length - 1;
int differ = 0 - nums[i];
while(left < right){
if(nums[left] + nums[right] == differ){
result.add(Arrays.asList(nums[i],nums[left],nums[right]));
while(left<right&&nums[left]==nums[left+1])left++;
while(left<right&&nums[right]==nums[right-1])right--;
left++;
right--;
}else if(nums[left]+nums[right]>differ){
right--;
}else{
left++;
}
}
}
}
return result;
}
}

4 Sum

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

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
public class {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length<4) return result;
Arrays.sort(nums);
for(int i = 0; i < nums.length-3; i++){
if(i>0&&nums[i]==nums[i-1])continue;
for(int j = i + 1; j< nums.length-2;j++){
if(j>i+1&&nums[j]==nums[j-1])continue;
int left = j+1;
int right = nums.length-1;
while(left<right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum==target){
result.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));
while(left<right&&nums[left]==nums[left+1])left++;
while(left<right&&nums[right]==nums[right-1])right--;
left++;
right--;
}else if(sum<target) left++;
else right--;
}
}
}
return result;
}
}