[leetcode] 1502. Can Make Arithmetic Progression From Sequence
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.
Example 1:
Input: arr = [3,5,1]
Output: true
Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
Example 2:
Input: arr = [1,2,4]
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
Constraints:
- 2 <= arr.length <= 1000
- -10^6 <= arr[i] <= 10^6
分析
题目的意思是:给你一个数组,判断能够组成间隔相等的序列。看了下面给出的例子之后,我第一反应就是先排序,然后再遍历一个个的求区间看相邻区间是否相等就行了。
代码
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
n=len(arr)
arr.sort()
for i in range(n-1):
if(i==0):
prev=arr[i+1]-arr[i]
else:
t=arr[i+1]-arr[i]
if(t!=prev):
return False
return True