移除元素-leetcode
1. 地址
https://leetcode-cn.com/problems/remove-element/
2. 思路
双指针思想,一个保存下一个合法元素应该存放的位置,一个遍历数组
3. 代码
class Solution {
/**
* @param Integer[] $nums
* @param Integer $val
* @return Integer
*/
function removeElement(&$nums, $val) {
$retCount = 0;
// $valCount = 0;
$originCount = count($nums);
foreach ($nums as $key => $num) {
if ($num != $val) {
$nums[$retCount] = $num;
$retCount ++;
}
}
// $retCount = $originCount - $valCount;
// var_dump($nums, $retCount);
return $retCount;
}
}
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/13046853.html