26. Remove Duplicates from Sorted Array

来源:互联网 发布:java基础讲解实战 编辑:程序博客网 时间:2024/05/16 19:25

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.

我采用的方法如下:

def removeDuplicates(self, nums):    """    :type nums: List[int]    :rtype: int    """    k = len(nums)#get the length of nums    if (k == 0):        return 0    elif (k == 1):        return 1    else:        i = 0        while i < k:            j = i + 1            if (j == k):                break            if (nums[i] == nums[j]):                del nums[j]                k = len(nums)            else:                i = j        return k
其他的方法:
class Solution(object):    def removeDuplicates(self, nums):        if len(nums)==0:            return 0        j=0        for i in range(1,len(nums)):            if nums[i]!=nums[j]:                nums[j+1]=nums[i]                j=j+1        return  j+1

原创粉丝点击