leetcode27_Remove Element

来源:互联网 发布:图片制作拼图软件 编辑:程序博客网 时间:2024/05/22 14:09

一.问题描述

Given an array and a value, remove all instances of that valuein 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

0 0