Leetcode OJ: Remove Duplicates from Sorted Array I/II
刪除排序數組重復元素,先來個簡單的。
Remove Duplicates from Sorted Array
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].
簡單粗暴,重復一個則偏移量加1,遍歷一次令A[i-k]=A[i]就可以了。看代碼:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 1) 5 return n; 6 int k = 0; 7 for (int i = 1; i < n; ++i) { 8 if (A[i] == A[i - 1]) { 9 ++k; 10 } else if (k > 0) { 11 A[i-k] = A[i]; 12 } 13 } 14 return n - k; 15 } 16 };題目加些條件:
Remove Duplicates from Sorted Array II
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].
允許重復出現兩次。
LZ比較實在,只是老實的把以上代碼的A[i]==A[i-1]的條件變成了i > 1 && A[i] == ?A[i-1] && A[i] == A[i-2]
然后果斷受教育
Input:[1,1,1,2,2,3]
Output:[1,1,2,3]
Expected:[1,1,2,2,3]
分析原因:A[i-2]有可能不是原來的值了,因為是連續判斷3個值,偏移只是偏移1個值,步長不對稱。 天真地以為只有這個坑,于是加了個對k的約束,判斷條件變成k != 1 && A[i] == A[i - 1] && A[i] == A[i - 2] 果斷再次受教育 Input:[1,1,1,1]Output:[1,1,1]
Expected:[1,1]
該偏移時不偏移了。 好吧,還是好好整理思路吧。 這里加的條件是允許2個,那如果條件逐漸變成允許3個、4個呢? 連寫幾個比較很明顯是不行的,而且還要考慮各種情況,很復雜,設計一個通用的方案更靠譜。 LZ想到的是計數的方法了,記錄上一次重復的次數,然后判斷次數是否允許,允許則進行偏移,不允許則偏移量加1。 且看代碼: 1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 int k = 0; 5 int count = 1; 6 for (int i = 1; i < n; ++i) { 7 if (A[i] == A[i - 1]) {8 count++;9 if (count > 2) { 10 k++; 11 continue; 12 } 13 } else { 14 count = 1; 15 } 16 if (k > 0) 17 A[i - k] = A[i]; 18 } 19 return n - k; 20 } 21 };?
轉載于:https://www.cnblogs.com/flowerkzj/p/3619490.html
總結
以上是生活随笔為你收集整理的Leetcode OJ: Remove Duplicates from Sorted Array I/II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MD5在线查询的实现
- 下一篇: JSP+JavaBean+Servlet