Two Sum - Less Or Equal
Example
Note
if (nums[left] + nums[right] <= target) {
res += right - left;
left++;
}Code
public class Solution {
/**
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
public int twoSum5(int[] nums, int target) {
// write your code here
// 2 7 11 15
if (nums == null || nums.length < 2) {
return 0;
}
Arrays.sort(nums);
int res = 0;
int left = 0, right = nums.length - 1;
while (left < right) {
if (nums[left] + nums[right] <= target) {
res += right - left;
left++;
} else {
right--;
}
}
return res;
}
}Last updated