Two Pointer

Two pointer 有两种解法:

1)l = 0, r = n - 1,两指针相向而行

2)l = 0, r = 1,两指针同向而行

经典题目

611 Valid Triangle Number

// 两指针相向而行
public int triangleNumber(int[] nums) {
    Arrays.sort(nums);
    int ans = 0;
    for(int l = 2; l < nums.length; l++) {
        int i = 0, j = l - 1;
        while (i < j) {
            if (nums[i] + nums[j] > nums[l]) {
                ans += j - i;
                j--;
            } else {
                i++;
            }
        }
    }
    return ans;
}

15 3Sum (with Dedup)

// Store the indexes of such tri-pairs.

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    if (nums == null) return res;
    
    Arrays.sort(nums);

    for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int sum = nums[left] + nums[right] + nums[i];
                if (sum < 0) {
                    left++;
                } else if (sum > 0) {
                    right--;
                } else {
                    res.add(Arrays.asList(i, left, right));
                    left++;
                    right--;
                }
            }
        }
    }
    return res;
}

Last updated