Remove Duplicates from Sorted Array
Links: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Description of the problem:
Given a sorted array, remove the duplicates in place such, all element appear only once and return the new length.
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 1 and 2 respectively. It doesn ' t matter what are you leave beyond the new length.
Hide Tags Array Pointers
Removes the repeated elements of I in the sorted array.
class Solution {public: int removeDuplicates(vector<int>& nums) { if(nums.size()<2)return nums.size(); int result=0; for(int i=1;i<nums.size();i++) { if(nums[i]!=nums[result]) nums[++result]=nums[i]; } return result+1; }};
There is also a simpler way to use the unique function in vectors.
class Solution {public: int removeDuplicates(vector<int>& nums) { nums.erase( unique(nums.begin(), nums.end() ), nums.end() ); return nums.size(); }};
26Remove Duplicates from Sorted Array