对撞型,灌水类
双指针算法普遍分为三种
对撞型指针的本质是,不需要扫描多余的状态。在两边指针的判断之后,可以直接跳过其中一个指针与所有另外一面 index 组成的 pair.
public class Solution {
/**
* @param nums: an array of integer
* @param target: an integer
* @return: an integer
*/
public int twoSum2(int[] nums, int target) {
// Write your code here
if(nums == null || nums.length == 0) return 0;
Arrays.sort(nums);
int count = 0;
int left = 0;
int right = nums.length - 1;
while(left < right){
if(nums[left] + nums[right] <= target){
left ++;
} else {
count += right - left;
right --;
}
}
return count;
}
}Trapping Rain Water
Last updated