"Leetcode" 83-remove duplicates from Sorted Array

Source: Internet
Author: User

Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.

Do the allocate extra space for another array, and you must does this on place with constant memory.

For Example,given input array nums = [1,1,2] ,

Your function should return length = 2 , with the first of the elements of nums being and 1 2 Respectivel Y. It doesn ' t matter what are you leave beyond the new length.

Error Solution:runtime Error

1 classSolution {2  Public:3     intRemoveDuplicates (vector<int>&nums) {4         if(Nums.size () <2)returnnums.size ();5          for(vector<int>::iterator Iter1=nums.begin (), Iter2=nums.begin () +1; Iter2!=nums.end (); iter1++,iter2++){6             if(*iter1==*iter2) nums.erase (iter1); //Here erase after the iter1 point to the element no longer exists, so Iter1 has been invalid 7         }8         returnnums.size ();9     }Ten};

Solution: "It doesn ' t matter what do you leave beyond the new length." The main thing is to understand this sentence, the original vector does not need to delete elements, with length to save the current subscript, until the next element to find a different and then + +

1 classSolution {2  Public:3     intRemoveDuplicates (vector<int>&nums) {4         if(Nums.size () <2)returnnums.size ();5         intLength=1;6          for(intI=1; I<nums.size (); i++){7             if(nums[i]!=nums[i-1])8nums[length++]=Nums[i];9             ElseTen                 Continue; One         } A         returnlength; -     } -};

"Leetcode" 83-remove duplicates from Sorted Array

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.