Remove Element of Leetcode

Source: Internet
Author: User

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn ' t matter what are you leave beyond the new length.

The requirement of the topic is this, the initial idea is very simple, first with a variable length of the array A, followed by an element in a traversal comparison, if the elements in a and ele the same, then the length minus 1

        int length = a.length;          for (int i = 0;i<a.length;i++) {            if(a[i] = = elem)                {= Length-1;            }        }         return length;        

After the submission of the error, I think the main reason is not to change the original array, only for the length of the array changes.

After modification:

 public  class   solution { int  removeelement (int  [] A, int  Span style= "color: #000000;"        > Elem) { int  length = 0< span> for  (int  i = 0;i<a.length;i++< Span style= "color: #000000;"                ) { if  (A[i]!= Elem) {                A[length]  = A[i];            Length  = length + 1;    }}  return   length; }}

Submitted successfully, then saw the online look at other people's methods, most people are if encountered Elem, it is adjusted to the back of the array,

 Public classSolution { Public intRemoveelement (int[] A,intelem) {        intLength =a.length;  for(inti = 0;i<length;i++){            if(A[i] = =elem) {A[i]= A[length-1]; I--; Length--; }        }        returnlength; }}

Think of it I and length processing there very well, take it for reference.

Remove Element of Leetcode

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.