2460. Apply Operations to an Array #1377
-
Topics: You are given a 0-indexed array nums of size You need to apply
After performing all the operations, shift all the
Return the resulting array. Note that the operations are applied sequentially, not all at once. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to apply a series of operations on an array of non-negative integers and then shift all zeros to the end of the array. The operations are applied sequentially, and each operation affects subsequent steps. Let's break down the approach and solution step-by-step. Approach
Let's implement this solution in PHP: 2460. Apply Operations to an Array <?php
/**
* @param Integer[] $nums
* @return Integer[]
*/
function applyOperations($nums) {
$n = count($nums);
for ($i = 0; $i < $n - 1; $i++) {
if ($nums[$i] == $nums[$i + 1]) {
$nums[$i] *= 2;
$nums[$i + 1] = 0;
}
}
$nonZeros = array();
foreach ($nums as $num) {
if ($num != 0) {
array_push($nonZeros, $num);
}
}
$zeroCount = $n - count($nonZeros);
for ($i = 0; $i < $zeroCount; $i++) {
array_push($nonZeros, 0);
}
return $nonZeros;
}
// Example test cases
$nums1 = [1,2,2,1,1,0];
$nums2 = [0,1];
print_r(applyOperations($nums1)); // Output: [1, 4, 2, 0, 0, 0]
print_r(applyOperations($nums2)); // Output: [1, 0]
?> Explanation:
This approach efficiently handles the operations and shifting in linear time, making it optimal for the given problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to apply a series of operations on an array of non-negative integers and then shift all zeros to the end of the array. The operations are applied sequentially, and each operation affects subsequent steps. Let's break down the approach and solution step-by-step.
Approach
Apply Operations Sequentially:
Shift Zeros to the End: