PythonTip >> 博文 >> python

[leetcode]Remove Element @ Python - 南郭子綦

zihua 2014-08-21 10:08:58 点击: 1701 | 收藏


原题地址:https://oj.leetcode.com/problems/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都换到数组的末尾去。

代码:

class Solution:
	# @param	A	   a list of integers
	# @param	elem	an integer, value need to be removed
	# @return an integer
	# clrs qsort
	def removeElement(self, A, elem):
		j = len(A)-1
		for i in range(len(A) - 1, -1, -1):
			if A[i] == elem:
				A[i], A[j] = A[j], A[i]
				j -= 1
		return j+1
原文链接:http://www.tuicool.com/articles/muAjIvv

作者:zihua | 分类: python | 标签: python | 阅读: 1701 | 发布于: 2014-08-21 10时 |