Published in
Dec 17, 2022
# 思路
這題主要是用雙指針的概念
$left 由 $nums 的第一個 index 開始, 也就是 0
$right 開始往後 loop, 只要 $right 當下的值跟 $left 不相同, 那就代表不同的數出現了, 這時就可以更新 $left 指針。
由於 $nums 本身是 sorted array, 因此可以保證只要 loop 到的值不等同 $left, 那就一定是一個新的數, 不可能是 $left 已經跑過的數。
由於 output 求的是重新排列後數組的長度 (不包含重複的數), 而 $left 是從 0 開始跑的, 因此要將 $left+1。
# 題目連結
# solution example
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function removeDuplicates(&$nums) {
$left = 0;
for ($right = 0; $right < count($nums); $right++) {
if ($nums[$right] !== $nums[$left]) {
$nums[++$left] = $nums[$right];
}
}
return $left+1;
}
}