日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode OJ: Remove Duplicates from Sorted Array I/II

發布時間:2025/4/9 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。