Leetcode oj_ (Python): 027-remove Element "Array" "Easy"

Source: Internet
Author: User
Tags array length

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"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.