package algorithm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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)) {
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));
}
}