259.较小的三数之和

【LeetCode刷题-双指针】--259.较小的三数之和-LMLPHP

方法:排序+双指针

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int k = 0;
        for(int i = 0;i<nums.length;i++){
            int start = i + 1,end = nums.length - 1;
            while(start < end){
                int sum = nums[start] + nums[end] + nums[i];
                if(sum < target){
                    k += (end - start);  //因为数组排好序了,所以start到end中的数都小于target
                    start++;
                }
                if(sum >= target){
                    end--;
                }
            }
        }
        return k;
    }
}
11-18 21:10