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

27. Remove elements

2022-06-11 05:17:00 qq_ twenty-six million three hundred and ninety-one thousand tw

/* Give you an array  nums  And a value  val, You need   In situ   Remove all values equal to  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)  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 .  Because it needs to be operated in situ , No auxiliary space , Consider double pointers l,r, distinguish val He Fei val  Loop traversal , When the left pointer is val, Right pointer is not val when , In exchange for l,r Value ,  When l==r, Exit loop , If at present l The value of is val, return l The first number is l, Otherwise return to l The previous number plus the current number l Corresponding elements , namely l+1 */

/** * @param {number[]} nums * @param {number} val * @return {number} */
var removeElement = function(nums, val) {
    
    if(!nums||!nums.length){
    
        return 0;
    }
    var l=0,r=nums.length-1;
    while (l<r){
    
        while (l<r&&nums[l]!==val){
    
            l++;
        }
        while (l<r&&nums[r]===val){
    
            r--;
        }
        var tmp=nums[l];
        nums[l]=nums[r];
        nums[r]=tmp;
    }
    return nums[l]===val?l:l+1;
};

原网站

版权声明
本文为[qq_ twenty-six million three hundred and ninety-one thousand tw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110508404881.html