welcome to Smartcat's cnblog

leetCode练题——26. Remove Duplicates from Sorted Array

1、题目

 

26. Remove Duplicates from Sorted Array--Easy

 

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

 

说实话,一开始真没看懂题目。后来才明白,是要把列表重复的数字去掉并且不增加多余的存储空间(体现在过程中),并且最后返回的是去重后的列表长度

2、我的解答

采用双指针法,i和j依次指向列表中的元素,一旦 i 和 j 不等,nums[j+1]=nums[i],具体如下:

 

# -*- coding: utf-8 -*-
# @Time    : 2020/2/2 12:23
# @Author  : SmartCat0929
# @Email   : 1027699719@qq.com
# @Link    : https://github.com/SmartCat0929
# @Site    :
# @File    : 26. Remove Duplicates from Sorted Array

from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        lens = len(nums)
        if lens > 0:
            j = 0
            for i in range(lens):
                if nums[j] != nums[i]:
                    j = j + 1
                    nums[j] = nums[i]
            nums= nums[0:(j + 1)]
            return j+1
print(Solution().removeDuplicates([1,2,2,3,3,5,5,5]))

 


 

posted @ 2020-02-03 11:29  聪明猫  阅读(107)  评论(0)    收藏  举报