Delete Element (Lintcode)

Source: Internet
Author: User

Delete ElementGiven an array and a value, delete the same number as the value in situ, returning the length of the new array.

The order of the elements can be changed and will have no effect on the new array.

Sample Example

Gives an array [0,4,4,0,0,2,4,4], and a value of 4

Returns a new array of 4 and 4 elements for [0,0,0,2]

The idea is to move elements except the deleted element to the leftmost, R is the right-most non-deleted element, and the right-most non-deleted element can be found at the beginning. Use I to iterate through the array, find the leftmost element, and assign the element r to position I. In the code, I first find the leftmost element, and then find the right-most non-deleted element. Time complexity is the same.

1  Public classSolution {2     /** 3      *@parama:a List of integers4      *@paramElem:an integer5      *@return: The new length after remove6      */7      Public intRemoveelement (int[] A,intelem) {8         intr = A.length-1;9         if(R < 0)return0;Ten         inti = 0; One          A          while(R >i) { -             if(A[i] = =elem) { -                  while(A[r] = = Elem && r > 0) r--; the                 if(R >i) { -A[i] =A[r]; -r--; -                 } +             } -i++; +         } A          at         if(A[r] = = elem) r--; -          -         returnR + 1; -     } -}
View Code

Delete Element (Lintcode)

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.