27. Remove Element (python)

Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Hint:
Try two pointers.
Did you use the property of “the order of elements can be changed”?
What happens when the elements to remove are rare?
题意:删除指定的元素值
要求不增加新的数组空间实现,且新数组后面的部分不影响
返回值为新数组的长度
思路:和26一样的,用两个指针,只要不等于指定值,就加入新数组
Runtime: 58 ms

class Solution(object):
    def removeElement(self, nums, val):
        if len(nums)==0:
            return 0
        j=0
        for i in range(len(nums)):
            if nums[i]!=val:
                nums[j]=nums[i]
                j=j+1
        return j

你可能感兴趣的:(leetcode)