题意:
解题思路:
思路:
1. 初始化 j = 0;
2. i从1开始遍历,如果nums[i]和nums[j]不相等,则表明找到了新的元素,让nums[j++] = nums[i]
3. 最后返回j+1,因为j从0开始;
PHP代码实现:
class Solution {
function removeDuplicates(&$nums) {
return $this->removeDuplicates1($nums);
$map = [];
foreach ($nums as $k => $num) {
if (in_array($num, $map)) unset($nums[$k]);
array_push($map, $num);
}
}
function removeDuplicates1(&$nums) {
if (count($nums) == 0) return 0;
$j = 0; $len = count($nums);
for ($i = 1; $i < $len; $i++) {
if ($nums[$i] != $nums[$j]) {
$j++;
$nums[$j] = $nums[$i];
}
}
return $j + 1;
}
}
GO代码实现:
func removeDuplicates(nums []int) int {
if len(nums) == 0 { return 0 }
j := 0
if len(nums) == 1 { return 1 }
for i := j + 1 ; i < len(nums); i++ {
if nums[i] != nums[j] {
j ++
nums[j] = nums[i]
}
}
return j + 1
}