https://leetcode.com/problems/check-if-it-is-a-straight-line/ Easy

Условие

Дан массив coordinates, где coordinates[i] = [x, y] — это координаты точки на 2D-плоскости. Нужно определить, лежат ли все точки на одной прямой.

Примеры

Input: [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true

Input: [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false

Решение

fun checkStraightLine(coordinates: Array<IntArray>): Boolean {
    val dx = coordinates[1][0] - coordinates[0][0]
    val dy = coordinates[1][1] - coordinates[0][1]

    for (i in 2 until coordinates.size) {
        val x = coordinates[i][0] - coordinates[0][0]
        val y = coordinates[i][1] - coordinates[0][1]
        if (dx * y != dy * x) return false
    }
    return true
}

Временная сложность

O(n), где n — количество точек.

Пространственная сложность

O(1), так как используются только переменные.