[LeetCode written test question] 27. Remove elements

Problem Description

Given an array nums and a value val, you need to remove in place all elements whose value is equal to val and return the new length of the array after removal.
Instead of using extra array space, you must 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.

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 is 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 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 is 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.

Problem-solving ideas

Find the elements in the array and compare them with the specified number. If they are equal, delete them. Use two pointers, one pointer is used to traverse the elements in the array to see which element is equal to the specified value, and the other is used to record the position where the next unequal element needs to be overwritten when an element is deleted. Otherwise it may be lost.

Illustration of this question

Code for this question

int removeElement(int* nums, int numsSize, int val) {
    
    int src=0;
    int dst=0;
    while(src<numsSize)
    {
        if(nums[src]!=val)
        {
            nums[dst++]=nums[src++];
        }
        else
        {
            src++;
        }
    }
    return dst;
}

Guess you like

Origin blog.csdn.net/2301_78131481/article/details/134346635