[LeetCode] Remove Element
阿新 • • 發佈:2017-07-07
sta ins 來源 tex ould leave 重要 strong fun
Given input array nums =
題目內容
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.
題目思路
題目難度:easy
此題雖然不難,但是蘊含的思想非常重要。這個題目就是數組快慢指針的思想來源。設定兩個指針,i和ii,其中i是慢指針,ii是快指針。初始化的時候,ii和i均等於0。快指針遍歷所有的數組,當nums[ii]!=val,則將nums[ii]賦值給nums[i],然後i+=1。此時i就是刪除了指定元素後的數組長度。
Python代碼
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i=0 for ii in range(0,len(nums)): if nums[ii]!=val: nums[i]=nums[ii] i+=1 return i
[LeetCode] Remove Element