[leetcode]#27. Remove Element

来源:互联网 发布:下载小林铜排计算软件 编辑:程序博客网 时间:2024/06/08 11:20

题目:
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.
题意:
给定一个数组和一个值,将数组里所有等于这个值的元素全部移除。
不要分配额外空间给新的数组,空间复杂度为O(1).
数组元素的顺序可以改变。

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