原題地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/
題意:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
解題思路:使用一個指針j,當i向后遍歷數組時,如果遇到與A[j]不同的,將A[i]和A[j+1]交換,同時j=j+1,即j向后移動一個位置,然后i繼續向后遍歷。
代碼:
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if len(A) == 0: return 0 j = 0 for i in range(0, len(A)): if A[i] != A[j]: A[i], A[j+1] = A[j+1], A[i] j = j + 1 return j+1
