码迷,mamicode.com
首页 > 其他好文 > 详细

26. Remove Duplicates from Sorted Array

时间:2017-02-05 12:25:20      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:other   beyond   space   move   appear   leetcode   span   with   .com   

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

标签:other   beyond   space   move   appear   leetcode   span   with   .com   

原文地址:http://www.cnblogs.com/prmlab/p/6367276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!