https://leetcode.com/problems/height-checker Easy

Решение

fun heightChecker(heights: IntArray): Int {
    // Подсчитываем количество каждого роста
    val count = IntArray(101)
    for (h in heights) {
        count[h]++
    }

    var index = 0
    var result = 0

    // Восстанавливаем отсортированный массив и сравниваем с оригиналом
    for (h in count.indices) {
        while (count[h] > 0) {
            if (heights[index] != h) result++
            index++
            count[h]--
        }
    }

    return result
}