描述
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
要求时间复杂度为O(n),空间复杂度为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; } };
以上是我自己看完题目后所编写的程序
分析:
len是数组元素的个数
first为第一个元素下标,second为第二个元素下标(如果数组只有一个元素,则不会进入循环,而是直接返回1)
index为复制后数组的个数
以下是参考LeetCode中使用STL实现的代码
代码1:
class Solution { public: int removeDuplicates(char a[], size_t len) { return distance(a, unique(a, a + len)); } };
所使用的函数:
template <class ForwardIterator> ForwardIterator unique ( ForwardIterator first, ForwardIterator last );
distance (InputIterator first, InputIterator last);
代码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++ = first; first = upper_bound(first,last,*first); } return output; } };
所使用的函数:
template <class ForwardIterator, class T> ForwardIterator upper_bound ( ForwardIterator first, ForwardIterator last, const T& value );
时间: 2024-10-04 16:54:54