從LeetCode學演算法 - 5 In-Place

0026. Remove Duplicates from Sorted Array (Easy)

Chih-Yu Lin

--

Question:
Given a sorted nums array, remove the duplicates in-place such that each element appears 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.

分析/解題:
題目要求將一個已排序陣列中所有的重複數字刪去,使得這個陣列的每個數字只出現一次,並且必須要以in-place的方式來處理。
最終處理過後,回傳新陣列的長度。

題目其實並不困難,設定一個i用來記錄目前存放到哪個位置,
再設定一個j用以完整遍歷整個陣列,
每當發現有不同的數字時,就將j的數字塞到i的位置,再往下推進即可。

最後由於要回傳的是新陣列的長度,所以應該要回傳i+1。(陣列由0開始)

這邊要順便提到的一個名詞叫in-place algorithm
所謂的in-place,就是指所有的操作修改,除了一些計數用的變數外,
基本上都在原先的資料結構內解決,像這題就是完全只有操作原陣列。…

--

--

Chih-Yu Lin

LeetCode、Python、Java、Android;第11屆iT邦幫忙鐵人賽Software Development組優選(從LeetCode學演算法);HiSKIO特約講師;課程優惠: https://bit.ly/lc2022all ;合作請洽: learnwithdesolve@gmail.com