Leetcode: 27-Remove elements

27. Remove elements

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

Don't use extra array space, you must only use O(1) extra space and modify the input array in-situ.

The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

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

You don't need to consider the elements in the array beyond the new length.
Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

The function should return the 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 the elements in the array beyond the new length.

Problem-solving ideas

这道题容易犯一个错误,就是如果匹配到了val,可能会尝试去移动数组元素,
然后数组长度-1,但是这道题比较特殊,这边的数组的数组长度和数组做了封装,不能直接去删除那么又如何去控制返回的数组长度呢。

网上的解题思路:
其实!!我们可以借助其它的变量去控制数组长度,就是自定义一个变量,
当满足元素 == val值时,不添加到自定义变量控制的数组中,
不满足则添加进去,这样返回的自定义变量就可以控制住返回的数组长度,
返回自定义变量就可以返回删除val后的数组了!

Code

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        
        int count =0;
        for(int i=0; i<nums.length; i++){
    
    
            if(nums[i] == val){
    
    
            }else{
    
    
                nums[count] = nums[i];
                count++;
            }
        }
        return count;
    }
}

test

Insert picture description here

Guess you like

Origin blog.csdn.net/JAYU_37/article/details/107251473