Algorithm double pointer problem solution

Time:2021-2-26

The use of double pointer in the algorithm sometimes feels very clever and solves a lot of problems. It is necessary to sum up. First of all, double pointer is a very broad concept, which is similar to traversalI and jBut the difference is that the two pointers move at the same time, that is, there is no contribution to the complexityO(N)reachO(N*N)Therefore, it is highly praised by many algorithm masters, so based on this, we summarize the common solutions and routines of double pointer.

1. Summary of questions

There are three types of questions

  • Speed pointer (two pointers that are not synchronized)

  • Front and back double ended pointer (one at the head, one at the tail, close to the middle)

  • Fixed spaced pointers (two pointers spaced I, I + k)

As mentioned earlier, these three kinds of pointers can be completed by traversing the array once, and their time complexity is less than or equal toO(N)The space complexity isO(1)Because only two pointers are stored.

2. Common questions

2.1 speed pointer

A classic question:

Through two hands with inconsistent steps, one moves forward and the other moves backward until the hands overlap

https://leetcode.com/problems/linked-list-cycle/descriptionThe code fragment is as follows:

public boolean hasCycle(ListNode head) {
    ListNode slow = head;
          ListNode fast = head;
    while (slow != null && fast != null) {
                 ListNode n = fast.next;
     fast = n == null ? null : n.next;
     if (slow == fast) {
         return true;
     }
                 slow = slow.next;
    }
    return false;
    }

The code solution is as follows:

public int findDuplicate(int[] nums) {
        //It will be seen as a circular list, speed pointer loop
        int index1 = 0;
        int index2 = 0;
        do
        {
            index1 = nums[index1];
            index2 = nums[index2];
            index2 = nums[index2];
            
        }while (nums[index1] != nums[index2]);
        index1 = 0;
//Find out in which position as the starting point, we can prove that we must meet at the starting point of the circle
        while(index1 != index2){
            index1 = nums[index1];
            index2 = nums[index2];
        }
        return index1;
    }

2.2 front and rear end pointer

  • Binary search

Binary search is a typical question type of front and back pointer

public static int binarySearch(int[] array, int targetElement) {
    int leftIndex = 0, rightIndex = array.length - 1, middleIndex = (leftIndex + rightIndex) / 2;
    
    while(leftIndex <= rightIndex) {
      int middleElement = array[middleIndex];
      if(targetElement < middleElement) {
        rightIndex = middleIndex - 1;
      }else if(targetElement > middleElement) {
        leftIndex = middleIndex + 1;
      }else {
        return middleIndex;
      }
      
      middleIndex = (leftIndex + rightIndex) / 2;
    }
    
    return -1;
  }

2.3 fixed interval pointer

//When Q goes to the end, P goes to the middle.

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode p = head, q = head;
        while (q != null && q.next != null) {
            q = q.next.next;
            p = p.next;
        }
        return p;
    }
}
//Fast and slow pointer, first let the fast pointer walk K steps, and then two pointers walk synchronously. When the fast pointer comes to the end, the slow pointer is the last K node of the list.

    public ListNode getKthFromEnd(ListNode head, int k) {
        
        ListNode frontNode = head, behindNode = head;
        while (frontNode != null && k > 0) {

            frontNode = frontNode.next;
            k--;
        }

        while (frontNode != null) {

            frontNode = frontNode.next;
            behindNode = behindNode.next;
        }

        return behindNode;
    }

3. Template summary

After reading the three codes, do you think it’s very simple? Let’s summarize the three code templates with double pointers

//1. Speed pointer
l = 0
r = 0
While has not been traversed
  If certain conditions
    l += 1
  r += 1
Return the appropriate value

//2. Left and right endpoint pointer
l = 0
r = n - 1
while l < r
  I found it
    Return the value found
  If certain conditions1
    l += 1
  Some conditions 2
    r -= 1
Return not found

//3. Fixed spacing pointer
l = 0
r = k
While has not been traversed
  Custom logic
  l += 1
  r += 1
Return the appropriate value

Wu Xie, little third master, is a rookie in the field of big data and artificial intelligence.
Please pay more attention
file