LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Link: Remove Element

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 for this question is to delete the specified element in an array and return the length of the new array. The element sequence of the new array can be changed.

The idea of this question is to use two pointers, l and r. l records the next position (that is, the current length of the new array) that does not contain the specified element. r traverses the array from the beginning, if the number at the r position is equal to the specified number, it is not processed. If the number at the r position is not equal to the specified number, you need to place the number at the r position in the l position and Add 1 to the l position.

Time Complexity: O (n)

Space complexity: O (1)

1 class Solution 2 {3 public: 4 int removeElement (int A [], int n, int elem) 5 {6 if (n = 0) 7 return 0; 8 9 int l = 0; 10 for (int r = 0; r <n; ++ r) 11 if (A [r]! = Elem) 12 A [l ++] = A [r]; 13 return l; 14} 15 };

Reprinted please note the Source: LeetCode --- 27. Remove Element

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.