[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