leetcode 26. Remove Duplicates from Sorted Array 详解 python3

一.问题描述

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 numsbeing modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

二.解题思路

这题主要是在审题了。

一开始我以为是那种随机无序的数组,又要求空间复杂度O(1),就只能nums.count(num)来判断是否是1然后再 del nums[i],一提交结果TLE, 马上一声wc出来,赶紧看下题目,题目说的是有序数组,这就,容易多了。

首先因为是有序数组,就可以保证:相同的元素肯定是挨在一起的,而不是像无序数组那样到处跑。

然后题目要求数组的前t个数是那t个不重复的数就好了。

那么解法就是:

swap,交换(本来题目也是要求我们in_place改变,要改数组的前几个值让他们为不重复元素)。

因为是有序数组,所以我们顺序遍历,如果碰到一个在之前迭代里没出现的数(因为是一个有序数组,所以判断一个数是否在之前迭代里出现与否很简单,只需要判断它与它前一位的数是否相同就行了,而不用多开空间来看),那么它一定是一个我们需要放在nums前面(不重复元素)中的数之一,我们把它交换到前面,然后这个数后面的几个数,如果是重复的那就不管它继续迭代,如果不是重复就继续交换到前面去。既然要交换,那肯定得有交换的索引。

用一个初始值为0的指针i来指向当前已处理好了,0~i都是不重复的元素。

然后遍历一次nums,假设索引是j,如果nums[j]!=nums[i],就让nums[i+1]=nums[j],然后i+1,

假设j是重复元素中第一个该元素的索引,你会发现nums[j-1]和nums[i]相同,因为通过交换,我们已经把上一个不重复元素保存到nums[i]里面了,和上一段说的如何找之前迭代里没出现的数原理是一样的。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        i=0
        for j in range(1,len(nums)):
            if nums[j]!=nums[i]:
                nums[i+1]=nums[j]
                i+=1
        return i+1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章