首页 > 其他 > 详细

259. 3Sum Smaller

时间:2016-06-22 12:48:01      阅读:189      评论:0      收藏:0      [点我收藏+]
    /*
     * 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;
        }

 

259. 3Sum Smaller

原文:http://www.cnblogs.com/zmyvszk/p/5606658.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!