LeetCode27. Remove element [simple]-double pointer

Title description:

To give you an array of nums and a value of val, you need to remove all elements with a value equal to val in place and return the new length of the array after the 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 the elements in the array beyond the new length.

My solution:

Like the previous question of deleting duplicate elements, the double pointer Dafa

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int dis=0;
        for(int i=0;i<nums.size();i++){
            if(nums[i]==val)   dis++;
            else nums[i-dis]=nums[i];
        }
        return nums.size()-dis;
    }
};

66 original articles published · Like1 · Visits 505

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105152544