Topic:
Given an array and a value, remove all instances of that value in place and return the new length.
Do the allocate extra space for another array, and you must does this on place with constant memory.
The order of elements can be changed. It doesn ' t matter what are 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 of the elements of nums being 2.
Given an array and a numeric Val, remove the number in the array equal to Val and return the length of the new array. You cannot request additional space beyond the new array length section to ignore.
Topic Ideas:
Since the given array has been sorted, then using i,j two subscript, I record the subscript of the new array, J is the original array subscript;
If NUMS[J]! = val, then nums[i] = nums[j],i,j each + 1, and finally returns I
Code:
classsolution (object):defremoveelement (self, Nums, val):""": Type Nums:list[int]: type Val:int:rtype:int"""I=0 J=0 Size=Len (nums) whileJ <size:#Guaranteed Cycle End ifNUMS[J] = = val:#If there is the same number as ValJ + = 1Else: Nums[i]= Nums[j]#assigns the number of comparisons to the next numberi + = 1J+ = 1returnIif __name__=="__main__": S=solution ()Print(S.removeelement (Nums =[3, 2, 2, 3], val = 3))
Leetcode oj_ (Python): 027-remove Element "Array" "Easy"