package algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组
* <p>
* 注意:答案中不可以包含重复的三元组。
* 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],满足要求的三元组集合为:
* [
* [-1, 0, 1],
* [-1, -1, 2]
* ]
* 结论: test()没有去重的情况下,耗时是calculate()的9.4倍,数据越多越明显。
*
*
* @author dingwen
* 2021.06.18 09:20
*/
public class Algoriehm01 {
private static int[] nums = {-1, 0, 1, 2, -1, -4, -8, 8, 6, 36, -56, -41, -10, 10, 4, 3, -3, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -13, -14, -15, -16, -17, -18, -19, -20, -21, -22,-50,-51,-52,-53,-54,-55,-56,-57,-58,-59,-60,52,53,54,55,56,57,58,59,60};
public static void main(String[] args) {
viewTime(true,"calculate");
viewTime(false,"test");
}
public static List<List<Integer>> calculate() {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length < 3) {
return result;
}
// 双轴快排 实现
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
int left = 0;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (i == left || i == right) {
break;
}
if ((num + sum) < 0) {
left++;
}
if ((num + sum) > 0) {
right--;
}
if ((num + sum) == 0) {
result.add(Arrays.asList(nums[left], nums[i], nums[right]));
break;
}
}
}
return result;
}
public static List<List<Integer>> test() {
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
for (int k = 0; k < nums.length; k++) {
if ((nums[i] + nums[j] + nums[k] == 0)) {
//todo 重复值处理
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return result;
}
public static void viewTime(boolean flag,String title) {
long start = System.nanoTime();
if (flag) {
System.out.println("calculate() = " + calculate());
} else {
System.out.println("test() = " + test());
}
long end = System.nanoTime();
System.out.println(title + "耗时 = " + (end - start));
}
}