题目:
我的解法:暴力法
思路:写出4个数的全排列,判断4个数之和是否等于target,将符合条件的数组由小到大排列,再存入HashSet去重。
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums.length<4){
return new ArrayList<List<Integer>>();
}
HashSet<List<Integer>> sites = new HashSet<List<Integer>>();
for(int i=0; i<nums.length; i++){
for(int j=i+1; j<nums.length; j++){
for(int k=j+1; k<nums.length; k++){
for(int l=k+1; l<nums.length; l++){
List<Integer> list = new ArrayList<Integer>();
if((nums[i]+nums[j]+nums[k]+nums[l])==target){
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
list.add(nums[l]);
System.out.println(list);
list.sort(Comparator.naturalOrder());
sites.add(list);
}
}
}
}
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(List<Integer> each: sites){
result.add(each);
}
return result;
}
}
官方题解:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> quadruplets = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 4) {
return quadruplets;
}
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break;
}
if (nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
for (int j = i + 1; j < length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if (nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break;
}
if (nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
int left = j + 1, right = length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/4sum/solution/si-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。