Leecode no.18 四數之和
阿新 • • 發佈:2020-12-08
package com.example.demo.leecode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 四數之和等於目標
* @Date 2020/12/8
* @author Tang
*
* 給定一個包含 n 個整數的陣列 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,b,c 和 d ,
* 使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。
* 注意:答案中不可以包含重複的四元組。
*/
public class FourSumTarget {
private Set<List<Integer>> resultSet = new HashSet<>();
public List<List<Integer>> execute(int[] nums, int target){
if(nums.length < 4){
return new ArrayList<>();
}
nums = sort(nums, 0, nums.length - 1);
//外層迴圈獲取第一位數 a
for(int i = 0; i < nums.length - 3; i++){
int a = nums[i];
//內層迴圈第二位數字 b
for (int j = i + 1; j < nums.length - 1; j++) {
int b = nums[j];
int index1 = j + 1;
int index2 = nums.length - 1;
int c = nums[index1];
int d = nums[index2];
while(index1 < index2){
if(a + b + c + d > target){
index2--;
d = nums[index2];
}else if(a + b + c + d < target){
index1++;
c = nums[index1];
}else{
//成功相等
setResultList(a, b, c, d);
index2--;
d = nums[index2];
}
}
}
}
List<List<Integer>> resultList = new ArrayList<>();
resultList.addAll(resultSet);
return resultList;
}
private void setResultList(int a, int b, int c, int d){
List<Integer> result = new ArrayList<>();
result.add(a);
result.add(b);
result.add(c);
result.add(d);
resultSet.add(result);
}
/**
* 快排
*/
private int[] sort(int[] nums, int left, int right){
if(left >= right){
return nums;
}
int i = left;
int j = right;
int base = nums[i];
while(i < j){
int temp = 0;
while(nums[j] > base){
j--;
}
if(i < j){
temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
i++;
}
while(nums[i] < base){
i++;
}
if(i < j){
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j--;
}
}
nums[i] = base;
int[] sortLeft = sort(nums, left, i - 1);
int[] sortRight = sort(sortLeft, i +1, right);
return sortRight;
}
public static void main(String[] args) {
int[] nums = {6,4,8,7,5,9,3,1,6,6,9,1};
int[] nums2 = {1,0,-1,0,-2,2};
int[] nums3 = {0,0,0,0};
List<List<Integer>> execute = new FourSumTarget().execute(nums3, 0);
for (List<Integer> i: execute) {
System.out.print(i);
}
}
}