首页 > 代码库 > 26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

https://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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn‘t matter what you leave beyond the new length.

 

 

Analysis

We can apply the fast-and-slow-pointer technique to solve this problem.  One slower pointer i denotes the location of the comparable number,  while the fast pointer j traverses the rest of rest of the array to find duplicates. 

 

The idea is to compare the first character with the second character, if the second character is not  duplicated, then  swap the first character with the second, however, if the second character is not  duplicated, advance the fast pointer j to the next character and swapping repeatedly until it reaches the end. Then move the slower pointer i from the first character to the second character, and compare the second character with the third, forth, fifth character and so on. 

 

Finally, the new array has the length of i+1. 

 

Solution

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
        print j + 1
        return j+1
nums=[1,2,3,3,4,4,8]
obj= Solution()
obj.removeDuplicates(nums)
print(nums)

 

 

Notes

 

4 space indentation after line def

 

 

My ans 

 

26. Remove Duplicates from Sorted Array