【LeetCode】-27. Remove elements

1. Question

27. Remove elements - Likou

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

Don't use 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.

illustrate:

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

Please note that the input array is passed by "reference", which means that modifications to the input array in the function are visible to the caller.

// nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
int len = removeElement(nums, val);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

2. Example

输入:nums = [3,2,2,3], val = 3
输出:2, nums = [2,2]
解释:函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。你不需要考虑数组中超出新长度后面的元素。例如,函数返回的新长度为 2 ,而 nums = [2,2,3,3] 或 nums = [2,2,0,0],也会被视作正确答案。
输入:nums = [0,1,2,2,3,0,4,2], val = 2
输出:5, nums = [0,1,4,0,3]
解释:函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。注意这五个元素可为任意顺序。你不需要考虑数组中超出新长度后面的元素。

3. Analysis 

 logic

When moving elements in an array, the first thing that comes to mind is the fast and slow pointers. Let both the slow pointer and the fast pointer point to the first element first, in two cases:

(1) If the value pointed by the fast pointer is equal to val, then the slow pointer does not need to move, only the fast pointer moves

(2) If they are not equal, then the value of the slow pointer position is the value of the fast pointer position, and both the slow pointer and the fast pointer are +1

return

After the program is executed, the position pointed by slow is the position next to the last non-val element, which happens to be the number of new array elements. Just return slow directly.

 

4. Code implementation

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        //使用快慢指针,slow和fast都指向第一个元素,fast用来找非val元素
        int slow = 0;
        int fast = 0;

        while(fast < nums.size())
        {
            //1.fast指向的元素=val,什么都不用做,fast继续向后走
            if(nums[fast] == val)
            {  
                fast++;
            }
            else//2.fast指向的元素!=val,让slow位置的元素变成fast位置的元素,slow向后走一步,fast向后走一步
            {
                nums[slow] = nums[fast];
                slow++;
                fast++;
            }
        }
        return slow;
    }
};

Guess you like

Origin blog.csdn.net/gx714433461/article/details/129686279