[Leetcode] Remove duplicates from Sorted array II (array subscript operation)

Source: Internet
Author: User

Because the test instructions of this topic is to require us to operate on the original array, the operation becomes slightly more complicated, otherwise the direct use of map is the simplest.

The basic idea is to record two pointers, one is the current array, the other is the destination array, and note that if more than 2 repetitions are found, then the cur of the destination array will be blocked,

Until a different occurrence and then assign a value forward.

Class Solution {public:    int removeduplicates (vector<int>& nums) {    if (nums.size () ==0)    return 0;    int cur=1;  Modified after array of the lower punctuation     int sum=0,temp;      for (int i=1;i<nums.size (); i++)      {       temp=nums[i];       if (Nums[i]==nums[i-1])       {         sum++; if (sum<2)   {nums[cur]=temp;     cur++; }         }         else         {         sum=0;         Nums[cur]=temp;         cur++;         }      }      return cur;}    ;

There is an online solution, initially did not think, and later found that forgot to see the conditions---> array has been sequenced, so only judge Nums[i] and nums[i-2] is feasible.

If i sweep to the current element before index already exists two (note, because a is orderly, so only need to judge the first two lines), then I keep moving. Otherwise , the element I points to is added to index,index and i Move forward together.

Class Solution {public:    int removeduplicates (int a[], int n) {        if (n < 3)            return n;        int index = 2;        for (int i = 2; i < n; i + +)        {            if (a[i]! = a[index-2])                A[index + +] = A[i];        }        return index;    };



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Leetcode] Remove duplicates from Sorted array II (array subscript operation)

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.