100. Delete duplicate numbers in the sorted array

Source: Internet
Author: User

Given a sorted array, delete the repeating number in the original array so that each element appears only once and returns the length of the new array.

Do not use additional array space and must be done without additional space in place.

  Sample Example

To array a =[1,1,2], your function should return a length of 2, at which time a=[up].

This simple difficulty of the problem to train to the first time to think of solutions, first an ugly solution

1 intRemoveDuplicates (vector<int> &nums) {2         //Write your code here3         if(Nums.empty ()) {4             return 0;5         }6vector<int>::iterator it=Nums.begin ();7vector<int>:: iterator temp;8it++;9         intmark=nums[0];Ten          while(it!=Nums.end ()) { One             if(*it==Mark) { Atemp=it; -it=nums.erase (temp); -             } the             Else{ -mark=*it; -it++; -             } +         } -         returnnums.size (); +}

Two pointers one after the other, if back and before, after deletion, and move backward one bit.

At least this is the first to think, the following post a beautiful

1 intRemoveDuplicates (vector<int> &nums) {  2         if(Nums.empty ())return 0; 3         intCount=0; 4          for(intI=1; I<nums.size (); i++){  5             if(nums[i]!=Nums[count]) {  6count++;7nums[count]=Nums[i]; 8             }  9         }  TenNums.resize (count+1);  One         returncount+1;  A}

The array within the count+1 is the result, the number of >=count is overwritten into count, and then the excess is removed.

100. Delete duplicate numbers in the 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.