当前位置: 代码迷 >> 综合 >> Leetcode 1502. Can Make Arithmetic Progression From Sequence
  详细解决方案

Leetcode 1502. Can Make Arithmetic Progression From Sequence

热度:8   发布时间:2023-12-12 21:00:39.0

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Can Make Arithmetic Progression From Sequence

2. Solution

**解析:**Version 1,先排序,再判断其是否是算术(等差)数组。Version 2以空间换时间,找出最大最小值,最大最小值相等,则数全相同为等差数列,如果最大最小值之差不能整除数组长度减1,说明是非等差数列。构造等差数列,判断其是否是数组中的元素。

  • Version 1
class Solution:def canMakeArithmeticProgression(self, arr: List[int]) -> bool:if len(arr) == 2:return Truearr.sort()for i in range(2, len(arr)):if arr[i] - arr[i-1] != arr[i-1] - arr[i-2]:return Falsereturn True
  • Version 2
class Solution:def canMakeArithmeticProgression(self, arr: List[int]) -> bool:if len(arr) == 2:return Truestat = {
    }minimum = arr[0]maximum = arr[0]for x in arr:minimum = min(minimum, x)maximum = max(maximum, x)stat[x] = xif maximum - minimum == 0:return Trueif (maximum - minimum) % (len(arr) - 1) != 0:return Falsestep = (maximum - minimum) // (len(arr) - 1)for x in range(minimum, maximum+1, step):if x not in stat:return Falsereturn True

Reference

  1. https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
  相关解决方案