首页 > 其他分享 >ThreeSum

ThreeSum

时间:2023-03-28 23:45:18浏览次数:34  
标签:right nums int result 数组 ThreeSum left

package AigorithmStudy.DoublePointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15.三数之和
 * 给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != j、i != k 且 j != k ,
 * 同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。
 * 注意:答案中不可以包含重复的三元组。
 * */

/**
 * 双指针: 时间复杂度:O(n^2)。 数组排序O(nlogn),遍历数组O(n),双指针遍历O(n),总体 O(nlogn) + O(n) * O(n),所以是O(n^2)
 * 1.特判:对于数组长度n,如果数组为null或者数组长度小于3,直接返回 []
 * 2.对数组进行排序
 * 3.遍历排序后的数组
 *    3.1 若num[0] > 0,直接返回结果。因为已经从小到大排好序了,后面不可能有三个数和 等于0
 *    3.2 对于重复元素:跳过,避免出现重复解
 *    3.3 令左指针 l = i+1,右指针 r = n-1,当 l<r 时,执行循环:
 *         3.3.1 若和大于0,说明 num[r]太大,r左移
 *         3.3.2 若和小于0,说明 num[l]太小,l右移
 *         3.3.3 当 num[i] + num[l] + num[r] == 0,执行循环,判断左界和右界是否和下一位重复,去除重复解,并同时将l,r移到下一位置,寻找新的解
 * */
public class ThreeSum {
    public static void main(String[] args) {
       int[] arr =  {-1,0,1,2,-1,-4};
        List<List<Integer>> result = new ArrayList<>();
        result = threeSum(arr);
        System.out.println(result);

    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                return result;
            }

            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }

            int left = i + 1;
            int right = nums.length - 1;
            while (right > left) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum > 0) {
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (right > left && nums[right] == nums[right - 1]) right--;
                    while (right > left && nums[left] == nums[left + 1]) left++;
                    right--;
                    left++;
                }
            }
        }
        return result;
    }
}

 

标签:right,nums,int,result,数组,ThreeSum,left
From: https://www.cnblogs.com/lipinbigdata/p/17267232.html

相关文章