259. 3Sum Smaller

class Solution {
    public int threeSumSmaller(int[] nums, int target) {
      Arrays.sort(nums);
      int count = 0;
      for(int i = 0; i < nums.length - 2; i++){
        int sum = target - nums[i];
        int j = i + 1;
        int k = nums.length - 1;
        while(j < k){
          int current_sum = nums[j] + nums[k];
          if(current_sum < sum){
            count += k - j;
            j++;
          }else{
            k--;
          }
        }
      }
      return count;
    }

}

 

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.

Example:

Input: nums = [-2,0,1,3], and target = 2
Output: 2 
Explanation: Because there are two triplets which sums are less than 2:
             [-2,0,1]
             [-2,0,3]

Follow up: Could you solve it in O(n2) runtime?

 

posted on 2018-07-18 08:30  猪猪&#128055;  阅读(91)  评论(0)    收藏  举报

导航