leetcode with python:27. Remove Element

题目:

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

这题跟26.Remove Duplicates from Sorted Array十分相似,不过这次要return的k为非目标数(val)的个数,同时把这些数移到阵列最前面
同样有记忆限制,不能再开其他阵列,仅能在这个阵列上进行操作
ex:[3,2,2,3],val=3 ==> return k=2 ,而此时的阵列为[2,2,x,x] (x为任意值)

和26.一样建立指标k来记录

class Solution:    def removeElement(self, nums: List[int], val: int) -> int:        k=0        for i in nums:            if i != val:                nums[k]=i                k=k+1        return k

当我们侦测到该位置值不等于val时,将该值往前面放
k代表了下次遇到符合条件的值要放的index,同时也能作为最后的回传值
由于实在跟26.太过相似,所以解释精简许多
最后执行时间为35ms(faster than 89.76%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章