leetcode-26-remove-duplicates-from-sorted-array
題目
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums
.
Consider the number of unique elements of nums
to be k
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the unique elements in the order they were present innums
initially. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
. - 題目連結
Example 1
1 | Input: nums = [1,1,2] |
Example 2
1 | Input: nums = [0,0,1,1,1,2,2,3,3,4] |
解釋題目
給你一個 array ( 叫 nums ),要把 nums 中重複的值去除,題目要求不能用新的 array 紀錄,只能更動原本的 array,最後,要回傳 array 中不重複數字的數量,假設是 k。驗證答案時,只會取 array 中前 k 個值,k 之後的值不會影響驗證。
思路
這題跟 leetcode-27 很像,差異是 leetcode-27 是去除 array 中指定的數字,這題是去除 array 中所有重複的數字,也就是所有數字只能出現一次。
- 在一次的 for 迴圈中,把 array 重新排列
- 因為要重新排列 array,所以必須有一個 new_index 去記錄 array 中每個位置,決定該位置要放甚麼數字
- new_index 會從 1 開始,因為第一個數字,一定不會有重複問題
- 遍歷 array 的過程中
- 如果
array[i]
的值 不等於 前一個數字array[new_index-1]
,array[new_index]
會替換成array[i]
,且 new_index 要往下走一步 - 如果
array[i]
的值 等於 前一個數字array[new_index-1]
,new_index 維持原位
- 如果
要注意的是,跟前一個數字比較是用
array[new_index-1]
而不是array[i-1]
,因為 array 是會變動的,但是因為array[new_index-1]
已經是變動完的結果,所以 new_index 所在位置的前值是確定的。這個前值,也可以用另外的變數表示,這邊可以跟 leetcode-80 比較。
程式碼
1 | class Solution: |