leetcode259,中文版是付费题,今天面试遇到的
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?
public int threeSmallTarget(int[] nums,int target){
if(arr.length < 3)
return 0;
int result = 0;
int len = nums.length;
Arrays.sort(nums);
for(int i = 0;i<=len-3;i++){
int l = i + 1;
int r = len - 1;
while(l<r){
if(nums[l]+nums[r]<target-nums[i]){
result = result + r - l;
l++;
}else{
r--;
}
}
return result;
}
}