The application of double pointers in problem-solving: same direction double pointer; opposite double pointer

1. Double pointers in the same direction:
Example: 19. Delete the Nth node from the bottom of the linked list.
Solution:
1. Define two pointers to point to the head of the linked list respectively.
2. One pointer moves by N bits first;
3. The two move together in the same direction. When the one that moves first reaches the end of the list, the one that moves later points to the Nth from the bottom.

2. Opposite double pointers:
Example: Solve the problem: 1. The sum of two numbers , find the sum of two numbers in the array is equal to the value of the target.
Solution:
1. After sorting the array, define two pointers to point to the beginning and the end of the value respectively;
2. If the sum is less than the target at this time, the "left pointer" moves one position to the right;
3. If the sum is greater than the target at this time, then The "right pointer" will move one position to the left.
4. Jump out of the loop when the sum is equal to the target.

to sum up:

1. Remember the common problem-solving ideas of common algorithms: same direction double pointer; opposite direction double pointer.

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/106818006