Q15. 3sum 双指针应用

一道题目令人想入非非的题。。。解法参考了评论区的答案(基本就是抄过来的)
先把输入数列排序,这样有两个好处:1.效率高:在进行2sum操作时一头一尾两个指针,2sum变成O(N)的复杂度。 2.解决了重复数字的问题
排序后在数组中先跳出一个数字,然后在剩余数组中进行2sum操作,这个算法的时间复杂度是O(N^2),运行速度也非常快,比97%的解法快。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new LinkedList<>();
        if(nums.length < 3)
            return ret;
        Arrays.sort(nums);        
        int i=0;
        while(i < nums.length-2){
            //System.out.println("loop start");
            //if the number is the same, continue
            if(i > 0 && nums[i] == nums[i-1]){
                i++;
                continue;
            }
            //sum is the summation of the next two numbers we are looking for
            int sum = 0 - nums[i];
            int lo = i+1, hi = nums.length-1;
            while(lo < hi){
                if(nums[lo] + nums[hi] == sum){
                    //System.out.println("find answer!!!!!!");
                    ret.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
                    while(lo < nums.length-1 && nums[lo] == nums[lo+1]) lo++;
                    while(hi > 0 && nums[hi] == nums[hi-1]) hi--;
                    lo++; hi--;
                }else if(nums[lo] + nums[hi] < sum)
                    lo++;
                else
                    hi--;                
            }     
            //System.out.println("loop");
            i++;
        }        
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44015873/article/details/86588598
今日推荐