Fast and slow pointers solve LeetCode array to remove elements

Title:

  1. Remove elements
    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 removed array.

Don't use extra array space, you have to use only 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.

illustrate:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed "by reference", which means that modifications to the input array within the function are visible to the caller.

You can imagine the internal operation as follows:

// nums is passed by "reference". That is, do not make any copies of the actual parameters
int len ​​= removeElement(nums, val);

// Modifications to the input array in the function are visible to the caller.
// Depending on the length returned by your function, it will print out all elements in the array within that length.
for (int i = 0; i < len; i++) { print(nums[i]); }

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, the new length returned by the function is 2, and nums = [2,2,3,3] or nums = [2,2,0,0], will also be considered 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 the new length 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.

hint:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

Ideas:

This question requires that no new space can be opened up, and only modification can be made in the original array. The idea is to define two pointers to point to the head of the array. The fast pointer Fast is responsible for quickly traversing the array, and the slow pointer Slow is responsible for keeping the values ​​in the array that are not equal to val in place. Overwrite, Slow will add one every time it is assigned, pointing to the next position.

		nums = [1,2,2,2,3,4,5,2,2]
		val = int(input("请输入目标值:"))
		Fast,Slow = 0,0
        for Fast in range(len(nums)):
            if nums[Fast] != val:
                nums[Slow] = nums[Fast]
                Slow += 1
        print(Slow)
        print(nums)

#Output
#请输入目标值:2
#4
#[1, 3, 4, 5, 3, 4, 5, 2, 2]

Guess you like

Origin blog.csdn.net/chenjh027/article/details/128171043