15. 三数之和

原题链接:https://leetcode-cn.com/problems/3sum/

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        // 首先数组进行排序【排序的目的是为了找出来的值不会重复】
        // 然后利用双指针法,把找三个元素换为找两个元素的思维
        List<List<Integer>> re = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++){
            if (nums[i] > 0){
                break;
            }
            // 有重读的直接跳过
            if (i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            // 数组最右边的指针
            int j = nums.length - 1;
            // 左边的指针
            int k = i + 1;
            // 要找的目标和【转换为两数之和】
            int target = 0 - nums[i];
            while(k < j){
                // 找到则加入到数组里面去
                if (nums[k] + nums[j] == target){
                    List<Integer> tempList = Arrays.asList(nums[i], nums[k], nums[j]);
                    re.add(tempList);
                    // 去除掉相同的值
                   while(k < j && nums[k] == nums[k+1]){
                       k++;
                   }
                   while(k < j && nums[j] == nums[j-1]){
                       j--;
                   }
                     k++;j--;
                } else if (nums[k] + nums[j] < target){
                    k++;
                } else{
                    j--;
                }
            }
        }
        return re;
    }
}

难点:

1 数组先排序,避免重复

2 双指针的做法,降低时间复杂度,【两数之和其实也可以用到双指针思量,结合起来】【三数之和变两数之和,相比两束之和,多一层次循环而已】 

posted on 2020-12-16 23:42  靠自己的骨头长肉  阅读(113)  评论(0编辑  收藏  举报