欢迎访问 生活随笔!

生活随笔

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

编程问答

[LeetCode] Remove Duplicates from Sorted Array II

发布时间:2025/5/22 编程问答 40 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [LeetCode] 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]

 

加一个变量记录一下元素出现的次数即可。这题因为是已经排序的数组,所以一个变量即可解
决。如果是没有排序的数组,则需要引入一个 hashmap 来记录出现次数。

 

方法1  用A[i] 和 A[index] 比较,同时,搞一个计数器

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个数的情况

1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if (n <= 2) return n; 5 int index = 2;//此方法可推广至最多允许k个数的情况,修改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 };

 

《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读

总结

以上是生活随笔为你收集整理的[LeetCode] Remove Duplicates from Sorted Array II的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。