3Sum Smaller

来源:互联网 发布:如何正确下载软件 编辑:程序博客网 时间:2024/04/20 09:00

Given an array of n integers nums and a target, find the number of index tripletsi, j, k with0 <= i < j < k < n that satisfy the conditionnums[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(n2) runtime?

思路:题目只要求小于target的集合,不管重复,那么就是固定i, j和k开始搜,

sum >target的时候,k--;没有什么问题;

sum == target的时候,j,j+1,.....k-1, k,那么从j到k之间的nums[k] 绝对小于target,这样count += k-j;

再j开始挪动。这样j++;

这个题目跟之前的3sum的不同就是,== target的时候,j,k不能同时移动,要记住题目要求什么。

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


0 0
原创粉丝点击