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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章