1、题目
Given a sorted array nums, remove the duplicates in-place such that each element appear only onceand 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 ofnums
being1
and2
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 ofnums
being modified to0
,1
,2
,3
, and4
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]))
leedCode练题 —— 26. Remove Duplicates from Sorted Array
原文:https://www.cnblogs.com/Smart-Cat/p/12254967.html