3Sum Smaller

LintCode Q 918 - 3Sum Smaller

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.

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

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

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

Solution

Solution : Two Pointers

Code:

public int threeSumSmaller(int[] nums, int target) {

	int len = nums.length;
	int res = 0;

	Arrays.sort(nums);

	for (int i = 2; i < len; i++) {
		int left = 0, right = i - 1;
		while (left < right) {
			if (nums[left] + nums[right] + nums[i] >= target) {
				right--;
			} else {
				res += right - left;
				left++;
			} 
		}
	}

	return res;
}

   Reprint policy


《3Sum Smaller》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC