首页 > 编程语言 > 详细

leetcode 【 Remove Element 】python 实现

时间:2015-01-16 22:12:09      阅读:1786      评论:0      收藏:0      [点我收藏+]

题目:

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的,就与尾部元素交换;整个过程中维护尾部交换元素的指针位置

leetcode 【 Remove Element 】python 实现

原文:http://www.cnblogs.com/xbf9xbf/p/4229763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!