首页 > 其他 > 详细

Remove Duplicates from Sorted Array I&&II

时间:2014-10-01 18:08:01      阅读:224      评论:0      收藏:0      [点我收藏+]

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

 

可假设A[0...k-1]是递增且无重复元素的数组,那么每次让A[i]与A[k-1]比,如果相等,则跳过,不等,则放入A[k],k++

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

 

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

依然使用上面的方法.

 

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if( !A || n<1 ) return 0;
 5         int k = 1;
 6         for(int i=1; i<n; ++i)
 7             if( A[i] != A[k-1] ) A[k++] = A[i]; //A[i]与A[k-1]不等,那么肯定可以放进
 8             else if( A[i] == A[k-1] && ( k<2 || A[i] != A[k-2]) )  //A[i]与A[k-1]相等,但不与A[k-2]相等,说明不足2个,那么可以放进
 9                 A[k++] = A[i];
10         return k;
11     }
12 };

 

Remove Duplicates from Sorted Array I&&II

原文:http://www.cnblogs.com/bugfly/p/4003386.html

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