Leetcode 1502. Can Make Arithmetic Progression From Sequence

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1502. Can Make Arithmetic Progression From Sequence相关的知识,希望对你有一定的参考价值。

文章作者: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 True
        arr.sort()
        for i in range(2, len(arr)):
            if arr[i] - arr[i-1] != arr[i-1] - arr[i-2]:
                return False
        return True
  • Version 2
class Solution:
    def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
        if len(arr) == 2:
            return True
        stat = {}
        minimum = arr[0]
        maximum = arr[0]
        for x in arr:
            minimum = min(minimum, x)
            maximum = max(maximum, x)
            stat[x] = x
        if maximum - minimum == 0:
            return True
        if (maximum - minimum) % (len(arr) - 1) != 0:
            return False
        step = (maximum - minimum) // (len(arr) - 1)
        for x in range(minimum, maximum+1, step):
            if x not in stat:
                return False
        return True

Reference

  1. https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/

以上是关于Leetcode 1502. Can Make Arithmetic Progression From Sequence的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1502. Can Make Arithmetic Progression From Sequence

Leetcode-5175 Can Make Palindrome from Substring(构建回文串检测)

(Easy) Can Make Palindrome - LeetCode Contest (in progress)

Contest-LeetCode5175. Can Make Palindrome from Substring(unfinished)

LeetCode:1502. 判断能否形成等差数列(python3,javascript)

Two Wrongs Can Make a Right (and Are Difficult to Fix)