给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请
你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4] 输出:[[-1,-1,2],[-1,0,1]] 解释: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。 nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。 nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。 不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。 注意,输出的顺序和三元组的顺序并不重要。
堆排序+双指针
class Solution {public List<List<Integer>> threeSum(int[] nums) {heapSort(nums); List<List<Integer>> ans = new ArrayList<List<Integer>>();int length = nums.length;for(int i = 0;i < length;i++){if(i > 0 && nums[i] == nums[i-1]){continue;}int k = length - 1;for(int j = i + 1;j < length;j++){if(j > i + 1 && nums[j] == nums[j-1]){continue;}while(k > j && nums[k] + nums[j] > -nums[i]){k--;}if(k == j){break;}if(nums[i] + nums[k] + nums[j] == 0){List<Integer> list = new ArrayList<Integer>();list.add(nums[i]);list.add(nums[j]);list.add(nums[k]);ans.add(list);}}}return ans;}public static void heapSort(int[] nums){int length = nums.length;for(int i = length / 2 - 1;i >= 0;i--){my_Sort(nums,i,length);}for(int i = length - 1;i >= 0;i--){int temp = nums[0];nums[0] = nums[i];nums[i] = temp;my_Sort(nums, 0, i);}}public static void my_Sort(int[] nums,int parent,int length){int child = 2*parent + 1;int temp = nums[parent];while(child < length){if(child + 1 < length && nums[child + 1] > nums[child]){child++;}if(temp >= nums[child]){break;}nums[parent] = nums[child];parent = child;child = 2*parent + 1;}nums[parent] = temp;}
}- 首先调用heapSort方法对输入数组nums进行堆排序。
- 创建一个空的列表ans用于存储结果。
- 遍历排序后的数组,对于每个元素nums[i],如果与前一个元素相同则跳过,避免重复解。
- 设置两个指针j和k,其中j从i+1开始遍历,k从数组末尾开始向前移动。
- 如果j与前一个元素相同则跳过,避免重复解。
- 在循环中,当nums[k] + nums[j] > -nums[i]时,将k向前移动一位,缩小搜索范围。
- 如果k == j,说明没有找到满足条件的三元组,跳出内层循环。
- 如果nums[i] + nums[k] + nums[j] == 0,说明找到了一组满足条件的三元组,将其添加到结果列表ans中。
- 最后返回结果列表ans。
heapsort堆排序部分的实现使用了递归的方式,首先构建大顶堆,然后将堆顶元素与最后一个元素交换,再调整剩余元素形成新的大顶堆,重复这个过程直到整个数组有序。