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
1
2
3
4
5
6
7
8
9
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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/
如果有收获,可以请我喝杯咖啡!