Delete all elements in an array equal to a key

Source: Internet
Author: User

Title Description:

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

The idea of violence in this topic is to traverse through a pointer, and delete which element will move the elements forward one position. But the complexity of this time is so great that you may want to move a lot of elements.

Here is the idea of dividing in a quick sort: with two pointers, the latter pointer is used for traversal, the previous pointer as a tag, indicating that the element before the tag satisfies the requirements .

So the specific code:

int removeelement (vector<int> &arr, int elem) {//write your code hereint size = Arr.size (); if (size = = 0) {return 0;} int pre = -1;for (int cur = 0; cur < size; ++cur) {if (Arr[cur]! = elem) {++pre;if (cur! = Pre) {swap (Arr[pre], arr[cur]);}} If}//forreturn pre + 1;}

  

Delete all elements in an array equal to a key

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.