前往
大廳
主題

[LeetCode] 1502. Can Make Arithmetic Progression From Sequence 荒漠甘泉TAT

テリ君(福佬模式) | 2023-06-06 20:20:11 | 巴幣 6 | 人氣 193

題目:
A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.

Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.

欸對,就確認一個list裡面全部值是否可以成為等差數列

class Solution:
    def canMakeArithmeticProgression(self, arr) -> bool:
        arr.sort()
        diff = arr[1] - arr[0]
        for i in range(2, len(arr)):
            if arr[i] - arr[i - 1] != diff:
                return False
        return True

感覺比two sum簡單太多ㄌ= =

創作回應

Toyakoyo
用了sort, O(lnN*N) 感覺面試會被追問: O(N)?
2023-08-12 19:34:53

更多創作