259. 3Sum Smaller

    /*
     * 259. 3Sum Smaller
     * 2016-6-21 by Mingyang
     * Given an array of n integers nums and a target, 
     * find the number of index triplets i, j, k with 0 <= i < j < k < n 
     * that satisfy the condition nums[i] + nums[j] + nums[k] < target.
     * 这个题目就是翻版的3Sum,刚开始自己做逻辑有点乱
     * 如果小于target直接count += right-left;因为第二个是left的话,第三个从left+1到right都是合法的
     * 不用一个一个判断,另外,每次完了以后left++,另外若小于,自然是right--
     */
     public static int count;
     public static int threeSumSmaller(int[] nums, int target) {
            count = 0;
            Arrays.sort(nums);
            int len = nums.length;
            for(int i=0; i<len-2; i++) {
                int left = i+1, right = len-1;
                while(left < right) {
                    if(nums[i] + nums[left] + nums[right] < target) {
                        count += right-left;
                        left++;
                    } else {
                        right--;
                    }
                }
            }

            return count;
        }
原文地址:https://www.cnblogs.com/zmyvszk/p/5606658.html