码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode] Remove Duplicates From Sorted Array II (C++)

时间:2014-11-05 01:51:40      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   for   sp   

题目:

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

Tag:

Array; Two Pointers

体会:

继续是quicksort中partition函数的改写。和Remove Duplicates From Sorted Array只有一处变化。这次的变化是第10处的那个判断条件多了一部分 A[len - 1] != A[i] 。从A[0]到A[len]是满足题意要求的部分, 如果现在正在检查的这个element已经在A[0]-A[len]出现过了,但是只要它在最近的两个中没有出现,还是可以加到现在的部分中的。

 1 class Solution {
 2     public:
 3         int removeDuplicates(int A[], int n) {
 4             // length of satisfied part
 5             int len = -1;
 6             for (int i = 0; i < n; i++) {
 7                 // if it is unique to current satisfied part 
 8                 // or it has not shown within last two positions
 9                 // in current satisfied part
10                 if (A[i] != A[len] || A[len - 1] != A[i]) {
11                     len++;
12                     A[len] = A[i];
13                 }
14             }
15             return len + 1;
16         }
17 };

 

[Leetcode] Remove Duplicates From Sorted Array II (C++)

标签:style   blog   http   io   color   ar   os   for   sp   

原文地址:http://www.cnblogs.com/stevencooks/p/4075247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!