"Algorithms that programmers must master" Double pointers "Part 1"

Double pointers (Two Pointers) are one of the common methods to solve algorithmic problems. It solves the problem by maintaining two pointers that wander in a certain sequence. The most common double pointer problem is to find whether there are two numbers in a sorted array whose sum is equal to the target value.

Specifically, let a pointer left initially point to the first element of the array, and a pointer right initially point to the last element of the array. We then compare their sum to the target value each time:

  • If the sum of the two numbers is equal to the target value, the result is returned directly;
  • If the sum of the two numbers is less than the target value, move the left pointer one position to the right;
  • If the sum of the two numbers is greater than the target value, move the right pointer one position to the left.

Keep moving the pointer in this way until the target value is found or left >= right. Here is a sample code:

public boolean twoSum(int[] nums, int target) {
    
    
    int left = 0, right = nums.length - 1;
    while (left < right) {
    
    
        int sum = nums[left] + nums[right];
        if (sum == target) {
    
    
            return true;
        } else if (sum < target) {
    
    
            left++;
        } else {
    
    
            right--;
        }
    }
    return false;
}

It is worth noting that this assumes that the elements in the array are ordered. If there is no sorting, we can sort first and then use double pointers to solve the problem. Of course, there are also some problems where double pointers can be used without sorting, such as reversing strings, linked lists, etc.

In addition, the algorithm for maintaining two pointers is not limited to the sum of two numbers. For example, to find the longest palindrome substring in a string, we can use two pointers to continuously expand to determine whether the current substring is a palindrome. For the specific solution to this problem, please refer to my blog "The Longest Palindrome Substring".

In short, double pointers are a simple and effective way to solve algorithmic problems, and programmers must master them in daily development.

Guess you like

Origin blog.csdn.net/qq_45704048/article/details/132824428