the sum of three integers

3Sum(the fifteenth question of leetcode)
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Notice that the solution set must not contain duplicate triplets.

快速排序+双指针夹逼,注意相邻值相等时要跳过,否则方案重复

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
       int len = nums.length;
       //从小到大排序
       quickSort(nums, 0, nums.length - 1);

       List<List<Integer>> result = new ArrayList<>();
       
       //双指针找数
       for(int i =0;i<len-2;i++){
           if(nums[i]>0) return result;
           if(i>0 && nums[i] == nums[i-1]) continue;
           List<List<Integer>> temp = towSum(nums, i);
           if(!temp.isEmpty()){
               result.addAll(temp);
           }
       }
       return result;
    }

    public void quickSort(int[] nums, int left, int right){
        if(left>=right) return;
        int tempVal = nums[left];
        int i =left, j=right;
        while(i<j){
            while(j>i && tempVal<=nums[j])j--;
            if(i<j){
                nums[i++] = nums[j];
            }
            while(j>i && tempVal>=nums[i])i++;
            if(i<j){
                nums[j--] = nums[i];
            }
            // System.out.printf("%d %d\n", i, j);
        }
        nums[i] = tempVal;
        quickSort(nums, left, i-1);
        quickSort(nums, i+1, right);
   }

   public List<List<Integer>> towSum(int[] nums, int targetIndex){
        List<List<Integer>> group = new ArrayList<>();
        int i = targetIndex +1, j=nums.length-1;
        int target = -1 * nums[targetIndex];
        while(i<j){
           if(nums[i] + nums[j] == target){
               List<Integer> temp = new ArrayList<Integer>();
               temp.add(nums[targetIndex]);
               temp.add(nums[i]);
               temp.add(nums[j]);
               group.add(temp);

               while(j>i && nums[j-1] == nums[j])j--;
               while(j>i && nums[i+1] == nums[i])i++;

               i++;
               j--;
           }else if(nums[i] + nums[j]<target){
               i++;
           }else{
               j--;
           }
        }
        return group;
   }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值