原題地址: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
