-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveElement.php
More file actions
50 lines (47 loc) · 1.44 KB
/
Copy pathRemoveElement.php
File metadata and controls
50 lines (47 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
namespace App;
/**
* RemoveElement.php
*
* Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order
* of the elements may be changed. Return k after placing the final result in the first k slots of nums.
* Do not allocate extra space for another array. You must do this by modifying the input array in-place
* with O(1) extra memory.
*
* Example 1:
* Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_]
* Explanation: Your function should return k = 2, with the first two elements of nums being 2.
* It does not matter what you leave beyond the returned k (hence they are underscores).
*
* https://leetcode.com/problems/remove-element
*/
class RemoveElement
{
/**
* @param array<array-key, int> $nums
* @param int $val
* @return int
*/
public function removeElement(array &$nums, int $val): int
{
for ($i = 0; $i < count($nums); $i++) {
if ($nums[$i] === $val) {
$this->deleteArray($nums, $i);
$i--;
}
}
return count($nums);
}
/**
* @param array<array-key, int> $arr
* @param int $index
* @return void
*/
private function deleteArray(array &$arr, int $index): void
{
for ($i = $index + 1, $iMax = count($arr); $i < $iMax; $i++) {
$arr[$i - 1] = $arr[$i];
}
array_splice($arr, count($arr) - 1, 1);
}
}