Describe
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 A = [1,1,2],
Your function should return length = 2, and A is now [all].
Requires a time complexity of O (n) and a space complexity of O (1)
#include <iostream> #include <assert.h> #include <vector> #include <algorithm>using namespace Std;class solution{public:int removeduplicates (char *a, size_t len) {assert (a); size_t index = 1;int first = 0;int second = 1;while (Second < Len) {if (A[second]! = A[first]) {a[index++] = A[second];first = second;} second++;} return index;};
The above is the program I wrote after I read the topic myself
Analysis:
Len is the number of array elements
First is the subscript for element one, second for the second element (if the array has only one element, it does not enter the loop, but returns 1 directly)
Index is the number of copied arrays
The following is the code implemented in the reference Leetcode using STL
Code Listing 1:
Class Solution{public:int RemoveDuplicates (char a[], size_t len) {return distance (a, unique (a, A + Len));}};
The functions used are:
Template <class forwarditerator> forwarditerator unique (forwarditerator first, ForwardIterator last);
Distance (inputiterator first, Inputiterator last);
Code Listing 2:
Class Solution{public:int RemoveDuplicates (char a[], size_t len) {return _removeduplicates (a,a+len,a)-A;} Template<class t1,class t2>t2 _removeduplicates (T1 First, T1 last, T2 output) {while (first! = last) {*output++ = firs T;first = Upper_bound (First,last,*first);} return output;}};
The functions used are:
Template <class ForwardIterator, class t> ForwardIterator upper_bound (forwarditerator first, ForwardIterator last , const t& value);
This article is from the "Zero Egg" blog, please be sure to keep this source http://lingdandan.blog.51cto.com/10697032/1769832
Array--remove duplicates from Sorted array