码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array II

时间:2015-04-28 18:13:26      阅读:113      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!