[leetcode]Remove Duplicates from Sorted Array @ Python


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM