删数组某项--Remove Element

https://leetcode.com/problems/remove-element/

Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

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

题意:删去数组中某数值项,不用保持原来顺序,返回新数组长度

解题思路:去掉数组中等于elem的元素,返回新的数组长度,数组中的元素不必保持原来的顺序。使用头尾指针,头指针碰到elem时,与尾指针指向的元素交换,将elem都换到数组的末尾去。但注意指针 i 是从后面遍历。

 1 class Solution:
 2     # @param {integer[]} nums
 3     # @param {integer} val
 4     # @return {integer}
 5     def removeElement(self, nums, val):
 6         A=nums
 7         j=len(A)-1                       #指针j指向尾部
 8         for i in range(len(A)-1,-1,-1):  #之所以逆序遍历,后面的数都已经过判断不是val,这样换到前面才不会出错
 9             if A[i]==val:                #若从前面开始遍历,和后面的数交换,i继续遍历,于是此数没有继续判断的机会了,说不定也是val
10                 A[i],A[j]=A[j],A[i]
11                 j-=1                     #交换一次,j向前移动把删除的val和最终的数组截断
12         return j+1                       #此时j+1即数组长度

 

posted @ 2015-07-05 11:35  小榛子  阅读(268)  评论(0编辑  收藏  举报