首页 > 代码库 > leetcode - Remove Duplicates from Sorted Array I && II

leetcode - Remove Duplicates from Sorted Array I && II

Remove Duplicates from Sorted Array I

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

 

Remove Duplicates from Sorted Array II

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,将整个数组看成两个部分,前半部分是符合题目要求的数组,后半部分是待探索的数组,设置两个用于遍历的变量index和i,index用于定位前半部分数组的末尾,i用于定位后半部分的数组,在两个部分之间的元素是被剔除的元素

2,同时设置一个变量count用于记录重复次数,再设置一个变量limit用于记录可重复的最大次数,这样一共4种情况,A[index] == A[i]时,count大于limit或者count不大于limit,A[index] != A[i]时,count大于limit或者count不大于limit

3,通过i的遍历,不断将符合题目要求的元素加入到前半部分数组中

代码:

 1 class Solution { 2 public: 3     int removeDuplicates(int A[], int n) { 4  5         if (n < 2) 6         { 7             return n; 8         } 9 10         const int limit = 2; //I设为1,II设为211         int index = 0, i = 1, count = 1;12 13         while (i < n)14         {15             if (A[index] == A[i])16             {17                 ++count;18                 if (count > limit)19                 {20                     ++i;21                 }22                 else23                 {24                     A[++index] = A[i++];25                 }26             }27             else28             {29                 A[++index] = A[i++];30                 count = 1;31             }32         }33 34         return index + 1;35     }36 };
View Code

 

通过这两个题目,可以总结出一个对数组进行处理的一般性方法(要求空间复杂度为常数),即将整个数组看成两个部分,前一部分是符合要求的,需要用一个变量来定位这个部分,后一部分是待处理的,通过一个变量来定位和遍历,这两部分中间可能有剩余元素(这部分是被处理过不合要求的),通过遍历处理后一部分的元素,将不断扩张前一部分的数组,直到后一部分的元素都遍历完,整个处理过程就结束了

 

leetcode - Remove Duplicates from Sorted Array I && II