马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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.
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
-106 <= arr[i] <= 106
Judy
Python merge sortclass Solution(object):
def canMakeArithmeticProgression(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
def mergesort(arr):
m = len(arr) // 2
if m == 0:
return arr
return merge(mergesort(arr[:m]), mergesort(arr[m:]))
def merge(a1, a2):
l1 = len(a1)
l2 = len(a2)
i1 = 0
i2 = 0
rlst = []
while i1 < l1 and i2 < l2:
if a1[i1] < a2[i2]:
rlst.append(a1[i1])
i1 += 1
else:
rlst.append(a2[i2])
i2 += 1
rlst.extend(a1[i1:])
rlst.extend(a2[i2:])
return rlst
l = len(arr)
if l <= 2:
return True
lst = mergesort(arr)
diff = lst[1] - lst[0]
for i in range(2, l):
if lst[i] - lst[i-1] != diff:
return False
return True
Python built_in function sortclass Solution(object):
def canMakeArithmeticProgression(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
arr.sort()
diff = arr[1] - arr[0]
length = len(arr)
for i in range(2, length):
if arr[i] - arr[i-1] != diff:
return False
return True
|