php code
while 状态:通过 执行用时:40 ms 内存消耗:16.8 MB
function removeDuplicates(&$nums) {
$max = count($nums);
if($max <= 0) return 0;
$j = 1;
$i = 0;
while($j<$max){
if($nums[$i] == $nums[$j]){
unset($nums[$j]);
} else {
$i = $j;
}
$j++;
}
return count($nums);
}
for 状态:通过 执行用时:16 ms 内存消耗:16.8 MB
function removeDuplicates(&$nums) {
$max = count($nums);
if ($max <= 0) return 0;
$n= $nums[0];
for ($i=1; $i<$max; $i++) {
if ($n != $nums[$i])
$n = $nums[$i];
else
unset($nums[$i]);
}
return count($nums);
}
java code
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
System.out.println(Arrays.toString(nums));
return i + 1;
}
}
本文介绍了解决LeetCode上删除排序数组中的重复项问题的PHP和Java代码实现。PHP部分使用了while和for循环,分别展示了两种不同的解决策略;Java部分则通过一次遍历实现了高效解法。

631

被折叠的 条评论
为什么被折叠?



