15. 三数之和

https://leetcode-cn.com/problems/3sum/

思路:

方法一:数组排序后,三重暴力循环,排序的目的是一种方便获得不重复解的手段

方法二:数组排序后,利用双指针,因为数组排序后,元素有小到大,便于和0进行比较;

package 数组;

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

public class 三数之和 {
    public static void main(String[] args) {
//        int[] nums = {-1, 0, 1, 2, -1, -4};
        int[] nums = {1,2,-2,-1};
//        int[] nums = {0,0,0};
        三数之和 三数之和 = new 三数之和();
        System.out.println(三数之和.threeSum(nums));
    }

    // 有序数组,双指针法
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        // {-4,-1,-1,0,1,2}
        // {-2,-1,1,2}
        for (int i = 0; i < nums.length - 1; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            int right = nums.length - 1;
            for (int j = i + 1; j < nums.length - 1; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) continue;
                while (j<right && nums[i] + nums[j] + nums[right] > 0) {
                    right = right - 1;
                }
                if(j == right){
                    break;
                }
                if (nums[i] + nums[j] + nums[right] == 0) {
                    ArrayList<Integer> oneResult = new ArrayList<>();
                    oneResult.add(nums[i]);
                    oneResult.add(nums[j]);
                    oneResult.add(nums[right]);
                    result.add(oneResult);
                }
            }
        }
        return result;
    }


    // 三数之和为零的,不包含重复结果
    // 暴力法
    public List<List<Integer>> threeSum1(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        // {-4,-1,-1,0,1,2}
        for (int i = 0; i < nums.length - 2; i++) {
            if (i != 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length - 1; j++) {
                if (j != i + 1 && nums[j] == nums[j - 1]) continue;
                for (int k = j + 1; k < nums.length; k++) {
                    if (k != j + 1 && nums[k] == nums[k - 1]) continue;
                    if (nums[i] + nums[j] + nums[k] == 0) {
                        ArrayList<Integer> oneResult = new ArrayList<>();
                        oneResult.add(nums[i]);
                        oneResult.add(nums[j]);
                        oneResult.add(nums[k]);
                        result.add(oneResult);
                    }
                }
            }
        }
        return result;
    }
}

 

posted @ 2021-11-20 16:49  guoyu1  阅读(63)  评论(0编辑  收藏  举报