首页 > 其他 > 详细

Remove Duplicates from Sorted Array II

时间:2015-04-28 18:10:29      阅读:212      评论:0      收藏:0      [点我收藏+]

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].

分析:从第三个数开始,每个数都只和它前面第二个数相比较,如果不同的话,则在结果中添加该数;如果相同,则不处理。运行时间21ms

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(n <= 2) return n;
 5         
 6         int index = 2;
 7         for(int i = 2; i < n; i++){
 8             if(A[i] != A[index-2]) A[index++] = A[i];
 9         }
10         return index;
11     }
12 };

 

Remove Duplicates from Sorted Array II

原文:http://www.cnblogs.com/amazingzoe/p/4463366.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!