Sponsored
Sponsored
This approach involves creating an 'expected' array by sorting the given 'heights' array. Once sorted, you compare each element of the original 'heights' array with the corresponding element in the 'expected' array. Count the number of mismatches, which will be your answer.
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) to store the 'expected' array.
1import java.util.Arrays;
2
3public class HeightChecker {
4 public static int heightChecker(int[] heights) {
5 int[] expected = heights.clone();
6 Arrays.sort(expected);
7 int count = 0;
8 for (int i = 0; i < heights.length; i++) {
9 if (heights[i] != expected[i]) {
10 count++;
11 }
12 }
13 return count;
14 }
15
16 public static void main(String[] args) {
17 int[] heights = {1, 1, 4, 2, 1, 3};
18 System.out.println(heightChecker(heights));
19 }
20}
In Java, use 'clone' to copy 'heights' to 'expected' and 'Arrays.sort()' to sort it. Compare elements of 'heights' and 'expected' to count mismatches.
Given the constraint that heights range between 1 and 100, we can use a counting sort based approach to find deviations from the expected array without explicitly sorting.
Time Complexity: O(n + k) where k is 100 (a constant, heights range). Space Complexity: O(k) for the count array.
1public class
In Java, use an array 'countHeights' to count occurrences of each height. Using these counts, simulate a sorted version for mismatch counting.