Skip to content

1051. Height Checker 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int heightChecker(vector<int>& heights) {
    int ans = 0;
    int currentHeight = 1;
    vector<int> count(101);

    for (int height : heights)
      ++count[height];

    for (int height : heights) {
      while (count[currentHeight] == 0)
        ++currentHeight;
      if (height != currentHeight)
        ++ans;
      --count[currentHeight];
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int heightChecker(int[] heights) {
    int ans = 0;
    int currentHeight = 1;
    int[] count = new int[101];

    for (int height : heights)
      ++count[height];

    for (int height : heights) {
      while (count[currentHeight] == 0)
        ++currentHeight;
      if (height != currentHeight)
        ++ans;
      --count[currentHeight];
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def heightChecker(self, heights: list[int]) -> int:
    ans = 0
    currentHeight = 1
    count = [0] * 101

    for height in heights:
      count[height] += 1

    for height in heights:
      while count[currentHeight] == 0:
        currentHeight += 1
      if height != currentHeight:
        ans += 1
      count[currentHeight] -= 1

    return ans