Python编程作业【第八周】(二)

LEETCODE


#27 Remove Element

Description:
    Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.
    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

这个问题和上一个问题比较类似,需要特别注意的是列表为空和列表当中只有一个元素的情况:

My solution:
    我认为这个题目的出题者的意图有歧义,因为在题目中已经要求了,只需要关心列表的前面若干个未删除的元素,但是在实际情况下,对于一个长度为1的列表,当这个列表当中唯一的元素被删除之后,本应该关注这个列表的前0个元素,也就是根本不必关心这个列表当中的元素,但是题目依然要求这个列表是空列表,那么标准output就和题目描述冲突了。

下面给出代码:

class Solution:
    def removeElement(self, nums, val):
        p = 0
        length = len(nums)
        if length == 0: return 0
        if length == 1: 
            if val == nums[0]: 
                nums.pop()
                return 0
            else: return 1
        for i in range(length):
            if nums[i] != val:
                nums[p] = nums[i]
                p += 1
        return p
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章