当前位置:网站首页>27. remove elements

27. remove elements

2022-06-25 07:50:00 AlbertOS

introduce

Give you an array n u m s nums nums And a value v a l val val, You need In situ Remove all values equal to v a l val val The elements of , And return the new length of the array after removal .

Don't use extra array space , You have to use only O ( 1 ) O(1) O(1) Additional space and In situ Modify input array .

The order of elements can be changed . You don't need to think about the elements in the array that follow the new length .

Example

Input :nums = [3,2,2,3], val = 3
Output :2, nums = [2,2]
explain : Function should return the new length 2, also nums The first two elements in are 2. You don't need to think about the elements in the array that follow 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], It will also be seen as the right answer .

Input :nums = [0,1,2,2,3,0,4,2], val = 2
Output :5, nums = [0,1,4,0,3]
explain : Function should return the new length 5, also nums The first five elements in are 0, 1, 3, 0, 4. Note that these five elements can be in any order . You don't need to think about the elements in the array that follow the new length .

Answer key

Just use the double pointer to cover the position of the element you want to delete , At last, just modify the length of the array , Here I use containers vector Store array , It can intelligently adjust the array length , It is more convenient than self adjustment ~

class Solution {
    
public:
    int removeElement(vector<int>& nums, int val) {
    
        int n = nums.size();
        int left = 0;
        for (int right = 0; right < n; right++) {
    
            if (nums[right] != val) {
    
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }
};

summary

Actually, I did a difficult problem today , But there is still room for improvement , I won't send that ~

原网站

版权声明
本文为[AlbertOS]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250550166805.html