Topic_Array——Remove Duplicates from sorted array

Given a sorted array nums, 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. 消除重复的数
  3. 不许开辟一个新的数组空间,只能用O(1)的新空间
  4. 返回两个值,一个是新数组的长度(由返回值返回)。一个是数组本身(形参为指针直接带回

题目思路: 

  有序数组的性质很好,一旦这个数出现结束后,在之后的遍历中就不会再出现;而且删除重复数以后的数组也是有序的。

  如果没有空间复杂度的控制,最简单的方式就是遍历一遍,把第一次出现的数存在一个新的数组中返回。

  在由空间复杂度控制的情况下,要充分利用原数组的空间,也就是在原数组中直接边遍历边移动各个元素的位置。 其中 two pointer方法比较常用:

  1.  two pointers : 2个指针的方法总体来说就是一个pointer_current指向目前正在遍历的数组,另一个pointer_next指向生成的新数组。这个方法非常广泛,一般来说两个指针的速度不同,pointer_current的速度是一定的,但pointer_next 就可以跳过不满足条件的元素。在本问题中,两个指针都在原数组中运动, 
posted on 2019-01-16 17:47  KissMe3Times  阅读(149)  评论(0)    收藏  举报