- Topic: 18 four and the number of
- Difficulty: Moderate
- Category: Array
- Solution: Dual Pointer
Today we learn to question 18 four and the number of which is a moderate problem. Topics such as the array of often face questions as to examine the interviewer algorithm capabilities and the ability to write code, so it is best experts to write the title. Here we look at this question in the title description.
Title Description
Given a n
integer array nums
and a target value target
, it is determined nums
whether there are four elements a
, b
, c
and d
, such that the a + b + c + d
value of target
equal to? Identify all satisfy the conditions of the quad and do not repeat.
Note: The answer can not contain duplicate quad.
Example:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
analysis
In the front, we did LeetCode-1 and two numbers and LeetCode-15 three digital sum , this topic is seeking four and the number of its basic ideas and triple the number of and about the same, and only three on the basis of the number of Add a for
loop. DETAILED solving process detailed LeetCode-15 and the number of three . java
Code shown below;
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null && nums.length < 4)
return res;
// 对数组排序
Arrays.sort(nums);
// 固定第一个数
for(int i=0; i<nums.length-3; ++i){
if(i!=0 && nums[i] == nums[i-1])
continue;
if(nums[i+1]>0 && nums[i] >= target)
return res;
// 固定第二个数
for(int j=i+1; j<nums.length-2; ++j){
if((j != i + 1) && nums[j] == nums[j-1])
continue;
// 使用左右指针进行查找
int left = j+1, right = nums.length-1;
while(left < right){
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if(sum == target){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[i]);
tmp.add(nums[j]);
tmp.add(nums[left]);
tmp.add(nums[right]);
res.add(tmp);
++left;
--right;
while(left<right && nums[left] == nums[left-1])
++left;
while(left<right && nums[right] == nums[right+1])
--right;
}else if(sum > target)
--right;
else
++left;
}
}
}
return res;
}
}
Github Address
LeetCode-18 four and the number of