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.
Class Solution {public: int removeduplicates (int a[], int n) { if (!n) return NULL; int num=1,i; for (I=1;i<n;++i) if (a[i]!=a[i-1]) a[num++]=a[i]; return num; }};
II. Add a Count variable to record the number of occurrences of key.
Class Solution {public: int removeduplicates (int a[], int n) { //Start Typing your C + + solution below //Do Not write int main () function if (n = = 0) return 0; int key = a[0]; int count = 0; int start = 0; for (int i = 0; i < n; i++) if (key = = A[i]) count++; else { for (int j = 0; J < min (2, count); j + +) a[start++] = key; key = A[i]; Count = 1; } for (int j = 0; J < min (2, count); j + +) a[start++] = key; return start; } };
How to prevent timeouts--remove duplicates from Sorted Array i&&ii