Leetcode 2sum 3sum 4sum 总结

本文详细解析了从2Sum到4Sum的算法问题,包括寻找数组中两数、三数及四数之和等于特定目标值的方法。通过双指针技术和哈希映射,文章提供了高效解决方案,并附带具体代码示例。

2 Sum 3 Sum and 4 Sum questions are similar, and the key of solving the problem is using 2 pointer.

2 Sum:

Question:

Given an array of integers that is already sorted in ascending order (why this condition is important? Because of the solution 1), find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

Solution 1:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
    	 // Create two pointers at the beginning and end of the array
    	 int i = 0, j = numbers.length - 1;
    	 while (i < j) {
    	 	if (numbers[i] + numbers[j] == target) {
    	 		break;
    	 	} else if (numbers[i] + numbers[j] > target) {
    	 		j--;
    	 	} else {
    	 		i++;
    	 	}
    	 }
    	 return new int[] {i+1, j+1};
    }
}

Solution 2: HashMap

class Solution {
    public int[] twoSum(int[] numbers, int target) {
    	Map<Integer, Integer> map = new HashMap<>();
    	for (int i = 0; i < numbers.length; i++) {
    		int complement = target - nums[i];
    		if (map.containsKey(complement)) {
    			return new int[] {i, map.get(complement)};
    		}
    		map.put(numbers[i], i);
    	}
    	throw new IllegalArgumentException("No Two Sum!");
    }
}

3 sum:

Question:

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.

Note:
The solution set must not contain duplicate triplets.
Example

Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

Note:

3 Sum can be regarded as an upgraded 2 Sum, meaning that we just need to fix one number of the three and then use the method in 2 Sum to find the remained two.

Solution:

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
    	List<List<Integer>> res = new ArrayList<>();
    	// Sort the array
    	Arrays.sort(nums);
    	for (int i = 0; i + 2 < nums.length; i++) {
    		if (i > 0 && nums[i] == nums[i - 1]) {
    			continue;
    		}
    		int target = -nums[i];
    		int j = i + 1, k = length - 1;
    		while (j < k) {
    			if (nums[j] + nums[k] == target) {
    				res.add(Arrays.asList(nums[i], nums[j], nums[k]));
    				j++;
    				k--;
    				while (j < k && nums[j] == nums[j - 1]) {
    					j++;
    				}
    				while (j < k && nums[k] == nums[k + 1]) {
    					k--;
    				}
    			} else if (nums[j] + nums[k] > target) {
    				k--;
    			} else {
    				j++;
    			}
    		}
    	}
    	return res;
    }
}

4 Sum:

Question:

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

Note:
The solution set must not contain duplicate quadruplets.

Note:

To resolve 3 Sum, we need to fix one of the three numbers and use the method of solving 2 sum to find the remaining 2 numbers. Similarly, to solve 4 sum, we need to fix two of the 4 numbers and use the method of 2 sum to find the remaining 2 numbers.

Solution:

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
    	List<List<Integer>> res = new ArrayList<>();
    	Arrays.sort(nums);
    	for (int i = 0; i + 3 < nums.length; i++) {
    		if (i > 0 && nums[i] == nums[i - 1]) {
    			continue;
    		}
    		for (int j = nums.length - 1; j >= i + 3; j--) {
    			if (j < nums.length - 1 && nums[j] == nums[j + 1]) {
    				continue;
    			}
    			int rest = target - nums[i] - nums[j];
    			int k = i + 1, h = j - 1;
    			while (k < h) {
    				if (nums[k] + nums[h] == rest) {
    					res.add(Arrays.asList(nums[i], nums[k], nums[h], nums[j]));
    					k++;
    					h--;
    					while (k < h && nums[k] == nums[k-1]) {
                            k++;
                        }
                        while (k < h && nums[h] == nums[h+1]) {
                            h--;
                        }
    				} else if (nums[k] + nums[h] > rest) {
    					h--;
    				} else {
    					k++;
    				}
    			}
    		}
    	}
    	return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值