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

 

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