您好,登錄后才能下訂單哦!
描述
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為復制后數組的個數
運行結果:
測試數組為 char a[16] = { 1, 1, 1, 2, 2, 2,2,5 ,6,6,6,6,7,7,8,9};
以下是參考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 );
================================================================
描述
Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?
For example, Given sorted array A = [1,1,1,2,2,3],
Your function should return length = 5, and A is now [1,1,2,2,3]
要求時間復雜度為O(n),空間復雜度為O(1)
class Solution2 { public: int removeDuplicates(int a[], size_t len) { return _removeDuplicates(a,a+len,a)-a; } template<class T1,class T2> T2 _removeDuplicates(T1 first, T1 last, T2 output) { T1 tmp = first; while (first != last){ if ((tmp!=first-1)&&(*tmp == *(first - 1))){ *output++ = *(first - 1); } *output++ = *first; tmp = first; first = upper_bound(first,last,*first); } return output; } };
以上代碼是我自己根據上題中使用STL進行部分代碼修改實現成功的程序
運行結果:
測試數組為 int a[16] = { 1, 1, 1, 2, 2, 2,2,5 ,6,6,6,6,7,7,8,9};
以下是參考LeetCode中實現的代碼
代碼1:
class Solution2 { public: int removeDuplicates(int *a,size_t len) { size_t index = 2; for (int i = 2; i < len ; ++i){ if (a[i] != a[index - 2]) a[index++] = a[i]; } return index; } };
代碼2:
class Solution2 { public: int removeDuplicates(int *a, size_t len) { int index = 0; for (int i = 0; i < len ; ++i){ if (i>0 && i<len-1 && a[i] == a[i - 1] && a[i] == a[i + 1]) continue; a[index++] = a[i]; } return index; } };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。