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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode] Remove Duplicates from Sorted Array II

發(fā)布時間:2025/5/22 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Remove Duplicates from Sorted Array II 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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]

?

加一個變量記錄一下元素出現(xiàn)的次數(shù)即可。這題因為是已經(jīng)排序的數(shù)組,所以一個變量即可解
決。如果是沒有排序的數(shù)組,則需要引入一個 hashmap 來記錄出現(xiàn)次數(shù)。

?

方法1 ?用A[i] 和 A[index] 比較,同時,搞一個計數(shù)器

1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if(n == 0) 5 return 0; 6 7 int index = 0; 8 int cnt=1; 9 for(int i = 1; i<n; i++) 10 { 11 if(A[index] != A[i]) 12 { 13 index++; 14 A[index]=A[i]; 15 cnt = 1; 16 } 17 else 18 { 19 if(cnt ==1) 20 { 21 index++; 22 A[index]=A[i]; 23 cnt +=1; 24 } 25 } 26 27 } 28 return index + 1; 29 } 30 };

方法2 ?用A[i] 和 A[index-1] 比較,此方法可推廣至最多允許k個數(shù)的情況

1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 2) return n; 5 int index = 2;//此方法可推廣至最多允許k個數(shù)的情況,修改inde的值即可 6 for (int i = 2; i < n; i++){ 7 if (A[i] != A[index - 2]) 8 A[index++] = A[i]; 9 } 10 return index; 11 } 12 };

?

《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的[LeetCode] Remove Duplicates from Sorted Array II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。