【LeetCode】——Dual pointers (fast and slow pointers)/multiple pointers

 =========================================================================

Homepage

code repository

C language column

Elementary data structure column

Linux column

=========================================================================


Preface

Hello everyone! This is a newly opened LeetCode question brushing column. This column is not just about randomly explaining some questions that I have practiced, but also summarizing some of my methods in answering questions that are applicable to a large category of questions. It is to provide everyone with this I hope that the problem-solving methods or ideas for large categories of questions can help some novices who are just starting to answer questions, and prevent them from giving up due to the difficulty of LeetCode when they first start solving questions. I also used it at the beginning. The most basic C language is explained.

In the first issue, what we bring to you today is double pointers , which can also be called fast and slow pointers, or even multiple pointers . This problem-solving method is mostly suitable for operating numbers in arrays, moving, deleting, etc. Without further ado, let’s start answering questions!

LeetCode 26. Remove duplicates in array

OJ link

Topic description:

Given an   array  that is not strictly increasingnums  , please delete the repeated elements in place so that each element  appears only once  , and return the new length of the array after deletion. The relative order of elements   should remain  consistent  . Then return  nums the number of unique elements in .

Considering  nums the number of unique elements is  k , you need to do the following to ensure that your solution can be passed:

  • Changes the array  nums so that  nums the previous  k element of contains unique elements,  nums arranged in the order in which they originally appeared in . nums The size of the remaining elements  nums does not matter.
  • Return  k .

Example 1:

Input: nums = [1,1,2] Output: 2, nums = [1,2,_]

Explanation: The function should return the new length 2, and the first two elements of the original array nums are modified to 1, 2. There is no need to consider the elements in the array that exceed the new length .
Example 2:
Input:
nums = [0,0,1,1,1,2,2,3,3,4]

Output: 5, nums = [0,1,2,3,4]

Explanation: The function should return a new length of 5, and the first five elements of the original array nums are modified to 0, 1, 2, 3, and 4. Elements in the array beyond the new length do not need to be considered.

Review summary: Give you an array, delete the same elements in the array, and return the length of the array.

Explanation of ideas:

Solution : Open two pointers that both point to the head. One pointer moves backward first and compares it with the previous number. If the value pointed by the previous pointer is equal to the value pointed by the next pointer, the latter pointer moves forward one bit, and then The former pointer continues to move until it is not equal to the value of the latter pointer. The value of the previous pointer is assigned to the value of the latter pointer. The latter pointer moves forward and the previous operation is repeated until the entire array is traversed. At this time, the latter pointer The pointer points to the last data in the array, and the returned value of this array plus 1 is the length of the array.

Interface code

    int left=0;
    int right=0;
    while(right<numsSize)
    {
        if(nums[right]==nums[left])
        {
            right++;
        }
        else
        {
            left++;
            nums[left]=nums[right];
        }
    }
    return left+1;

 LeetCode 27. Remove elements

OJ link

Topic description: 

Given an array nums and a value val, you need to remove all elements whose value is equal to val in place and return the new length of the array after removal.

NOTE : Do not use extra array space, you only use O(1) extra space and modify the input array in place. The order of elements can be changed. You don't need to consider elements in the array beyond the new length

Example 1:

Input: nums = [3,2,2,3], val = 3

Output: 2, nums = [2,2]

Explanation: The function should return the new length 2 , and the first two elements in nums are both 2 . You don't need to consider elements in the array beyond the new length. For example, if the new length returned by the function is 2, and nums = [2,2,3,3] or nums = [2,2,0,0], it will also be regarded as the correct answer.

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2

Output: 5, nums = [0,1,4,0,3]

Explanation: The function should return a new length of 5, and the first five elements in nums are 0, 1, 3, 0, 4. Note that these five elements can be in any order. You don't need to consider elements in the array beyond the new length.

Summary of the review: Given an array and a value, delete the elements in the array that are the same as the value and return the length of the array.

Explanation of ideas:

Solution 1: Create a new array

First of all, we will think of creating a new array, and put the values ​​that are not equal to val into the new array by traversing the values ​​​​in the original array. However, the space complexity of this idea is O(N), which is different from the space complexity required by the question. Degree O(1) is not met, so this idea does not work in this question .

Solution 2: Double pointers (fast and slow pointers)

Define two pointers at the beginning to point to the head of the array. The front pointer traverses the array. When the value of the current pointer is different from the value of val, the value of the front pointer is assigned to the next pointer, and the latter pointer is moved until the front pointer has traversed the entire array. Array, return pointer.

Interface code 

   int left=0;
    int right=0;
    for(right=0;right<numsSize;right++)
    {
        if(nums[right]!=val)
        {
            nums[left]=nums[right];
            left++;
        }
    }
    return left;

LeetCode 88. Merge two sorted arrays

OJ link

 Question description: You are given the sum of  two   integer arrays arranged in  non-decreasing ordernums1  , and  nums2two integer sums  m ,  n respectively representing   the number of elements in the sum. Please  merge it into   so that the merged array is also arranged in  non-decreasing order  .nums1nums2 nums2 nums1

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

Output: [1,2,2,3,5,6]

Explanation: Need to merge [1,2,3] and [2,5,6]. The merged result is [ 1 , 2,2 , 3,5,6 ], among which the elements in nums1 are marked in italics and bold.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0

Output: [1]

Explanation: Need to merge [1] and []. The combined result is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1

Output: [1]

Explanation: The arrays that need to be merged are [] and [1]. The combined result is [1]. Note that because m = 0, there are no elements in nums1. The only 0 left in nums1 is just to ensure that the merged result can be successfully stored in nums1.

Review summary:

You are given two arrays. The length of one array is equal to the sum of the valid data in the two arrays. Merge the short-length array into the long-length array and sort them.

Explanation of ideas: three pointers

Here we define three pointers pointing to the tail of the long array, the last valid data in the long array, and the tail of the segment array. They move forward in order to traverse the valid data in the long array and compare it with the data in the short array. Large values ​​are placed at the end of long arrays.

Here we also need to pay attention to a special situation : if each value in the segment array is smaller than the value of the valid data in the long array, the valid data in the long array has been moved, but the tail pointer of the short array has not been moved, so We can just move the values ​​in the short array to the long array. Because the question has already said that the order of right and wrong is in descending order .

Interface code

int end1=m-1;
int end2=n-1;
int end=m+n-1;
while(end1>=0&&end2>=0)
{
    if(nums1[end1]>nums2[end2])
    {
        nums1[end--]=nums1[end1--];
    }
    else
    {
        nums1[end--]=nums2[end2--];
    }
}
while(end2>=0)
{
    nums1[end--]=nums2[end2--];
}

That’s it for the three questions about fast and slow pointers in this issue. Here I just provide you with some ideas on how to solve the questions. I hope you can use them when solving questions in the future. Of course, fast and slow pointers are not only applicable to array questions. It can also be used in sequence lists and linked lists of data structures. It is not just two pointers, but even many.

Guess you like

Origin blog.csdn.net/qq_55119554/article/details/133191533