172. Remove Element "Lintcode by Java"

Source: Internet
Author: User
Tags lintcode

Description

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

The order of elements can changed, and the elements after the new length don ' t matter.

Example

Given an array [0,4,4,0,0,2,4,4] ,value=4

Return and front four elements of the 4 array is[0,0,0,2]

Problem solving: Today the topic is quite simple, given an array, and then given a value, requires the array in the existence of this value, are eliminated. On the basis of the original array, a rear is set as the subscript for the position to be inserted, starting from 0. Iterate over the array, if it is not value, place it in the rear position, and if so, do nothing until the loop ends. Finally, the rear value is returned, that is, the number of elements to remove value. The code is as follows:

1  Public classSolution {2     /*3 * @param a:a list of integers4 * @param elem:an integer5 * @return: The new length after remove6      */7      Public intRemoveelement (int[] A,intelem) {8         //Write your code here9         intRear = 0;Ten          for(inti = 0; i < a.length; i++){ One             if(A[i]! =elem) { Aa[rear++] =A[i]; -             } -         } the         returnRear; -     } -}

172. Remove Element "Lintcode by Java"

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.