D136 26. Remove Duplicates from Sorted Array
題目鏈接
26. Remove Duplicates from Sorted Array
題目分析
給定一個(gè)已經(jīng)排好序的數(shù)組,其中的整數(shù)會(huì)出現(xiàn)重復(fù)。需要在不增加內(nèi)存的情況下移除重復(fù)的元素。即不要新建數(shù)組。
注意,最后需要返回的是不重復(fù)的元素個(gè)數(shù)。
注意2,參數(shù)是以引用型傳過來的。
解題思路
逐個(gè)遍歷元素,先直接把當(dāng)前元素從數(shù)組中移除。
當(dāng)當(dāng)前元素和前一個(gè)元素不相同時(shí),做3件事情:
- 在原數(shù)組中插入這個(gè)不重復(fù)的元素。
- 記錄當(dāng)前數(shù)字,即最后出現(xiàn)的數(shù)字。
- 把下次要插入數(shù)字的下標(biāo)標(biāo)記為當(dāng)前下標(biāo)+1
最終代碼
<?php
class Solution {
/**
* @param Integer[] $nums
* @return Integer
*/
function removeDuplicates(&$nums) {
$index = 0;
$prev = NULL;
foreach($nums as $key => $num){
unset($nums[$key]);
if($num !== $prev){
$nums[$index] = $num;
$prev = $num;
$index = $key + 1;
}
}
return $index;
}
}
若覺得本文章對(duì)你有用,歡迎用愛發(fā)電資助。