题目描述:

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 by modifying the input array in-place with O(1) extra memory.

读入一个已经排序好的数组,让我们返回数组中未重复的数的个数。同时将数组整理下,把重复的部分去掉(超出真实个数的数组也是可以的,例如下面例子中要将数组整理为{1,2},但你整理成{1,2,2}也是可以的)。并且不能定义一个新的数组来完成这题。

例子:

1 Given nums = [1,1,2],
2 
3 Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
4 It doesn't matter what you leave beyond the new length.

解题思路:

既然题目要求不能定义一个新的数组,那我们只能在原来的数组上做文章。我们可以定义一个用于计数数组未重复部分的长度的int型数count。利用这是一个已排序好的数组,对整个数组进行循环。一开始count和i都是1,在循环中,若是nums[count-1]和nums[i]相同,则将i加1,count不变;若不一样,则同时加1。也就是说,把后面未重复的数推到前面,覆盖掉那些重复的数。

代码:

 

 1 int removeDuplicates(int* nums, int numsSize) {
 2     if(numsSize==0)
 3         return 0;
 4     int count=1;
 5     for(int i=1;i<numsSize;i++){
 6         if(nums[i]!=nums[count-1]){
 7             nums[count++]=nums[i];
 8         }
 9     }
10     return count;
11 }

 

posted on 2018-01-31 16:49  宵夜在哪  阅读(109)  评论(0编辑  收藏  举报