LeetCode Solutions

1051. Height Checker

Time:

Space:

			

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;
  }
};
			

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;
  }
}
			

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