[leetcode:python]27.Remove Element

来源:互联网 发布:苹果手机如何授权软件 编辑:程序博客网 时间:2024/05/29 17:17

题目:
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).
数组元素的顺序可以改变。

方法一:性能52ms

class Solution(object):    def removeElement(self, nums, val):        """        :type nums: List[int]        :type val: int        :rtype: int        """        if len(nums) == 0:            return 0        elif val not in nums:            return len(nums)        else:            while val in nums:                nums.remove(val)        return len(nums)

方法二:性能35ms

class Solution(object):    def removeElement(self, nums, val):        """        :type nums: List[int]        :type val: int        :rtype: int        """        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

其中,<> 表示不等于。

0 0
原创粉丝点击