leetcode 15 3Sum

题目详情

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

给定一个整数数组s,咱们要找出s中是否有三个不一样元素的加和等于0,若是有,输出全部知足条件的序列。要求序列不重复。数组

For example, 输入数组S = [-1, 0, 1, 2, -1, -4],
返回的结果集应该是:
[
[-1, 0, 1],
[-1, -1, 2]
]指针

想法

  • 经过减治的思想,咱们可把三个数求和的问题,减治为对于数组中不重复的元素nums[i],求两个数的和等于-nums[i]的过程。
  • 这个问题比较复杂的一点是,还要处理重复的数据。为了简化咱们的操做,咱们先对数组进行预排序。
  • 经历了预排序,咱们判断一个元素是否重复,只须要比较它和以前位置的元素是否相等就能够了。
  • 排序以后,对于求两个数和的问题,能够经过low和high两个指针从两边查找,也简化了操做时间。

解法

public List<List<Integer>> threeSum(int[] nums) {
        int length = nums.length;
         List<List<Integer>> res = new  ArrayList<List<Integer>>();
         Arrays.sort(nums);
        
         for(int i=0;i<length-2;i++){
             //防止重复序列
             if(i ==0 || (i>0 && nums[i] != nums[i-1])){
                 int low = i+1;
                 int high = length-1;
                 int target = -nums[i];
                 
                 while(low < high){
                     if(nums[low]+nums[high] == target){
                         res.add(Arrays.asList(nums[i], nums[low], nums[high]));
                         while(low < high && nums[low] == nums[low+1])low++;
                         while(low < high && nums[high] == nums[high-1])high--;
                         low++;
                         high--;
                     }else if(nums[low]+nums[high] < target){
                         low++;
                     }else{
                         high--;
                     }
                 }
             }
         }
        
        
        return res;
    }
相关文章
相关标签/搜索