leetcode27_Remove Element

橘子oly發表於2016-10-24

一.問題描述

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.

【注:個人認為本題最關鍵的資訊是 in place, 也就是要原地對陣列中的某元素,並返回移除後的新陣列的長度。也就是給定的陣列nums = [3,2,2,3],及元素val=3,經過程式處理後要變成nums = [2,2,x,x],並返回len=2】


二.演算法實現

    理解好了題意之後,演算法編寫還算簡單。程式碼如下:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        i = 0; j = 0
        while j<len(nums):
            if nums[j] == val:
                j += 1
            else:
                nums[i] =nums[j]
                i += 1
                j += 1
        return i

相關文章