zoukankan      html  css  js  c++  java
  • 3Sum

    Two pointers

    public class Solution {
        public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
            ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            Arrays.sort(num);
            int length = num.length;
            
            for(int i = 0; i< length; i++){
                int start = i+1;
                int end = length -1;
                int target = 0 - num[i];
                
                while (start< end){
                    if(target == num[start] + num[end]){
                        ArrayList<Integer> list = new ArrayList<Integer>();
                        list.add(num[i]);
                        list.add(num[start]);
                        list.add(num[end]);
                        result.add(list);
                        start++;
                        end--;
        /*filter the duplicate during two-pointer scan. For example [-2, 0, 0, 2,2], the expected output should be [-2,0,2]. If no filter here, the output will be duplicate as [-2,0,2] and [-2,0,2] */
                        while(num[start] == num[start-1] && start < end){
                            start++;
                        }
                        
                        while(num[end] == num[end+1] && start < end){
                            end--;
                        }
                        
                    }else if(target > num[start] + num[end]){
                        start++;
                    }else {
                        end--;
                    }
                    
                }
                //filter the duplicate for outside iteration. For example [-2, -2, -2, 0,2]. 最后一个是i+1,所以是i<length -1 
                 while((i< length-1) && num[i] == num[i+1]){
                     i++;
                 }
                
                
               
            }
            return result;
        }
    }
            
  • 相关阅读:
    Socket
    剑指 Offer 14- I. 剪绳子
    剑指 Offer 29. 顺时针打印矩阵
    判断二分图
    vue生命周期以及常用标签
    滑动窗口
    二叉树
    常用算法
    动态规划
    蓄水池抽样
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3533417.html
Copyright © 2011-2022 走看看