[Daily leavecode] Remove the element

Given an array of nums and a value of val, you need to remove all elements with a value equal to val in place, returning the new length of the removed array. Don't use extra array space, you have to modify the input array in place and use O(1) extra space. The order of the elements can vary. You don't need to consider elements in the array that are beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, the

function should return a new length of 2, and the first two elements in nums are both 2.

You don't need to consider elements in the array that are beyond the new length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2,

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 that are beyond the new length. Description: Why is the return value an integer, but the answer to the output is an array? Note that the input array is passed as a "reference", which means that modifying the input array in the function is visible to the caller. You can imagine the internal operation as follows:

// nums is passed as a "reference". In other words, do not make any copies of the actual parameters.
Int len ​​= removeElement(nums, val);

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

思维:Double pointer methodSet two pointers, a fast pointer j, a slow pointer i, if nums[j]==val, move backwards until it finds unequal Place it at nums[i] and add one to i. —————— Language: c++

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        if(nums.size()==0)
            return 0;
        sort(nums.begin(),nums.end());
        int i=0;
        for(int j=0;j<nums.size();j++)
        {
            if(nums[j]!=val)
            {               
                nums[i]=nums[j];
                i++;
            }
        }
        return i;
    }
};