zoukankan      html  css  js  c++  java
  • Leetcode015 3Sum

    public class S015 {
        public List<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            for(int i =0;i<nums.length;i++){
                if(i>0&&nums[i]==nums[i-1]){
                    continue;//重复的直接跳过
                }
                int left = i+1;//从i+1开始也是防止重复的办法
                int right = nums.length-1;
                while(left<right){
                    if(nums[left]+nums[right] == -nums[i]){
                        List<Integer> temp = new ArrayList<Integer>();//必须每次新建
                        temp.add(nums[i]);
                        temp.add(nums[left]);
                        temp.add(nums[right]);
                        Collections.sort(temp);
                        result.add(temp);
                        //特别注意下面两个while循环
                        left++;
                        right--;//防止重复                        
                        while(left<right&&nums[left]==nums[left-1]){
                            left++;//防止重复   
                        } 
                        while(left<right&&nums[right]==nums[right+1]){
                            right--;//防止重复   
                        }         
                        //这两个条件特别重要,思考一下为何分别是left++和right--;
                    }else if(nums[left]+nums[right] < -nums[i]){
                        left++;
                    }else{
                        right--;
                    }
                }
            }
            return result;
        }
    }
  • 相关阅读:
    定位小结
    定位知识点
    css属性书写顺序
    清除浮动及清除浮动的方法
    margin合并和塌陷问题
    css特性-层叠性,继承性,优先级
    css属性简写
    css布局之双飞翼布局
    css布局之圣杯布局
    css布局之等高布局
  • 原文地址:https://www.cnblogs.com/fisherinbox/p/5263820.html
Copyright © 2011-2022 走看看