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

Remove Duplicates from Sorted Array I&&II

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

标签:style   blog   color   io   os   使用   ar   for   sp   

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

标签:style   blog   color   io   os   使用   ar   for   sp   

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

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