leetcode brush to remove the title element -27-

Problem Description

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.

Examples

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.

achieve

Single pointer movement, the current value is not equal to the target value, a pointer is moved backward, the current value is equal to the target value, the pointer does not move, delete current element, the array length minus one

def remove_element(nums, val):

    nums_len = len(nums)
    index = 0

    while(index != nums_len):
        if(nums[index] == val):
            del(nums[index])
            nums_len -= 1
        else:
            index += 1

    return nums_len


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

result = remove_element(nums, val)
print(result)

to sum up

Often while loop is better than for loop, the boundary value is determined, the index value is set easier

Guess you like

Origin www.cnblogs.com/liuheblog/p/12296392.html