Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
1 // key is the moving location pointer 2 class Solution { 3 public: 4 int removeDuplicates(vector<int>& nums) { 5 int n = nums.size(); 6 if (n <= 1) return n; 7 8 int end = 0; 9 for (int i = 1; i < n; i++){ 10 if (nums[i] != nums[end]){ 11 end++; 12 //if (i!=end), actually the below line doesn't need to run 13 nums[end] = nums[i]; 14 } 15 } 16 17 return end+1; 18 } 19 };