leetcode 【 Remove Element 】python 实现

题目:

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.

 

代码 : oj测试通过 Runtime: 43 ms

 1 class Solution:
 2     # @param    A       a list of integers
 3     # @param    elem    an integer, value need to be removed
 4     # @return an integer
 5     def removeElement(self, A, elem):
 6         length = len(A)-1
 7         j = length
 8         for i in range(length,-1,-1):
 9             if A[i] == elem:
10                 A[i],A[j] = A[j],A[i]
11                 j -= 1
12         return j+1

 

思路:

顺序便利数组元素;遇到值等于elem的,就与尾部元素交换;整个过程中维护尾部交换元素的指针位置

posted on 2015-01-16 20:58  承续缘  阅读(392)  评论(0编辑  收藏  举报

导航