LeetCode 259. 3Sum Smaller 三数之和比target小的triplet有多少

168 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第13天,点击查看活动详情

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.

For example, given nums = [-2, 0, 1, 3], and target = 2.

Return 2. 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(n^2) runtime?

import java.util.Arrays;
 
/**
 * @Author you guess
 * @Date 2020/12/15 21:46
 * @Version 1.0
 * @Desc
 */
public class LeetCode_259_3SumSmaller {
 
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int low, high, sum;
        int count = 0;
        for (int i = 0; i < nums.length - 2; i++) {//只能遍历到最后三位,所以前面的只能到nums[len-3]
            low = i + 1;
            high = nums.length - 1;
            while (low < high) {
                sum = nums[i] + nums[low] + nums[high];
                if (sum < target) {
                    count += high - low;
                    low++;
                } else if (sum >= target) {
                    high--;
                }
            }
        }
        return count;
    }
 
    public static void main(String[] args) {
        LeetCode_259_3SumSmaller main = new LeetCode_259_3SumSmaller();
        System.out.println(main.threeSumSmaller(new int[]{-2, 0, 1, 3}, 5));//4
        System.out.println(main.threeSumSmaller(new int[]{-2, 0, 1, 3}, 2));//2
    }
 
}

end