27 Remove Element, 27 removeelement

Source: Internet
Author: User

27 Remove Element, 27 removeelement

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 you leave beyond the new length.

The requirement of the question is to give an array and a value, delete all elements with the same value in the array and return a new length.

Let's talk about the following ideas:

The double pointer and subscript I loop array can be used. Every time p_last subscript is traversed with I, when A [I] is the same as the given value, p_last is stopped, array length-1, I continues to pass the next value to A [p_last], if it is A [I] and value is different, let p_last + 1

The specific code is as follows:

 1 class Solution { 2 public: 3     int removeElement(int A[], int n, int elem) { 4        int length = n; 5        int p_last = 0; 6        for(int i=0;i<n;i++){ 7             A[p_last] = A[i]; 8             if(A[i] == elem) 9                 length--;10             else11                 p_last++;12        }13        return length;14     }15 };

Or you can have a more intuitive understanding:

The following code:

 1 class Solution { 2 public: 3     int removeElement(int A[], int n, int elem) { 4        int length = n; 5        int p_last = 0; 6         for(int i=0;i<n;i++){ 7             if(A[i]==elem){ 8                 length--; 9             }else{10                A[p_last] = A[i];11                p_last++;12             }13         }14        return length;15     }16 };

P_last indicates the subscript of the current "new" array, and the I loop array is A [I]! = Elem, assign values, and add p_last plus one "new" to the next element of the array to be inserted. I personally think this method is more intuitive.

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.