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;
}
}