26. Remove Duplicates from Sorted Array 解题记录

题目描述:

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 }

 

转载于:https://www.cnblogs.com/sakuya0000/p/8393173.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值