3Sum Smaller

题目地址:
https://leetcode.com/problems/3sum-smaller/description/

题目:
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(n2) runtime?

解题思路:
这道题就是运用双指针的解法。

代码:

public int threeSumSmaller(int[] nums, int target) {
    if(nums == null || nums.length <= 2){
        return 0;
    }
    Arrays.sort(nums);
    // assuming that there is not duplicate number in this array    int count = 0;
    int len = nums.length;
    for(int i = 0; i <= len - 3; i++){
        int j = i + 1, k = len - 1;
        int sum = target - nums[i];
        while(j < k){
            if(nums[j] + nums[k] < sum){
                count += k - j;
                j++;
                continue;
            }
            else{
                k--;
            }
        }
    }
    return count;
}



Comments

Popular Posts