1051. Height Checker #213
-
Topics: A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array You are given an integer array Return the number of indices where Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem at hand is to calculate the number of indices where the heights of students in a photo do not match the expected order. The students are supposed to be arranged in non-decreasing order by height. We are given the current arrangement and need to compare it with the expected arrangement to count how many students are out of place. Key Points:
Approach:
Plan:
Let's implement this solution in PHP: 1051. Height Checker <?php
/**
* @param Integer[] $heights
* @return Integer
*/
function heightChecker($heights) {
$ans = 0;
$currentHeight = 1;
$count = array_fill(0, 101, 0);
foreach ($heights as $height) {
$count[$height]++;
}
foreach ($heights as $height) {
while ($count[$currentHeight] == 0) {
$currentHeight++;
}
if ($height != $currentHeight) {
$ans++;
}
$count[$currentHeight]--;
}
return $ans;
}
// Example 1
$heights = [1,1,4,2,1,3];
echo heightChecker($nums, $k); // Output: 3
// Example 2
$heights = [5,1,2,3,4];
echo heightChecker($nums, $k); // Output: 5
// Example 3
$heights = [1,2,3,4,5];
echo heightChecker($nums, $k); // Output: 0
?> Explanation:The provided code uses a counting sort technique to avoid sorting the array completely. Instead of sorting, it counts the frequency of each height and then checks if the current height matches the expected height by incrementing through the counts.
Example Walkthrough:Example 1:
Example 2:
Example 3:
Time Complexity:
Output for Example:
The |
Beta Was this translation helpful? Give feedback.
The problem at hand is to calculate the number of indices where the heights of students in a photo do not match the expected order. The students are supposed to be arranged in non-decreasing order by height. We are given the current arrangement and need to compare it with the expected arrangement to count how many students are out of place.
Key Points:
Approach: