Topic_Array——Remove Element

Given an array nums and a value val, remove all instances of that value in-place 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.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

题目特点和要求:

  1. 去掉所有与指定数字的值相同的元素,将剩下元素按原来的顺序组合成新的数组
  2. 空间复杂度为:可以增加O(1)的空间
  3. 有两个返回值,一个是新数组的长度(返回值),另一个是新的数组(随形参的指针变量返回)
  4. 不需要管返回的新数组中长于新长度的部分。

题目思路:

  依旧是two pointers的思路,一个pointer_current指向正在遍历的原数组,一个pointer_next指向新生成的数列,由于空间复杂度的要求,所以两个指针都在原数组内,只不过一个快一个慢。

  还有一个思路适用于一种特殊情况:指定值不经常出现,或在数组靠后的位置出现。因为在这种情况下,two pointers需要不断的复制,这是比较消耗时间的。那么有一个新思路是,pointer_next 在大部分情况(没出现指定值)下,都与pointer_current一同变化,并且并不对原数组进行操作,直到出现指定值的情况下才进行操作。

 

posted on 2019-01-16 20:22  KissMe3Times  阅读(86)  评论(0)    收藏  举报