9. The algorithm is simple and swift removal of elements

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91527815

Given an array nums and a value val, you need to place the elements to remove all equal values ​​val, and returns the new length of the array after removal.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Order of the elements may be changed. You do not need to consider beyond the elements of the new array length behind.

Example 1:

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

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

You do not need to consider beyond the elements of the new array length behind.
Example 2:

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

New function should return the length 5 and the first five elements nums is 0, 1, 3, 0, 4.

Note that these five elements can be in any order.

You do not need to consider beyond the elements of the new array length behind.

solution:

 func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
        guard nums.count > 0 else {
            return 0
        }
        
        for (index,value) in nums.enumerated().reversed() {
            
            if(value == val){
                nums.remove(at: index)
                
            }
            
        }
        
        return nums.count;
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91527815