Judie 发表于 2023-6-6 13:32:28

【朱迪的LeetCode刷题笔记】1502. Can Make Arithmetic Progression From Sequence

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 =
Output: true
Explanation: We can reorder the elements as or with differences 2 and -2 respectively, between each consecutive elements.

Example 2:
Input: arr =
Output: false
Explanation: There is no way to reorder the elements to obtain an arithmetic progression.


Constraints:
2 <= arr.length <= 1000
-106 <= arr <= 106

Judy
Python merge sort
class Solution(object):
    def canMakeArithmeticProgression(self, arr):
      """
      :type arr: List
      :rtype: bool
      """
      
      def mergesort(arr):
            m = len(arr) // 2
            if m == 0:
                return arr
            return merge(mergesort(arr[:m]), mergesort(arr))
      
      def merge(a1, a2):
            l1 = len(a1)
            l2 = len(a2)
            i1 = 0
            i2 = 0
            rlst = []
            while i1 < l1 and i2 < l2:
                if a1 < a2:
                  rlst.append(a1)
                  i1 += 1
                else:
                  rlst.append(a2)
                  i2 += 1
            rlst.extend(a1)
            rlst.extend(a2)
            return rlst

      l = len(arr)
      if l <= 2:
            return True
      lst = mergesort(arr)
      diff = lst - lst
      for i in range(2, l):
            if lst - lst != diff:
                return False
      return True
Python built_in function sort
class Solution(object):
    def canMakeArithmeticProgression(self, arr):
      """
      :type arr: List
      :rtype: bool
      """

      arr.sort()
      diff = arr - arr
      length = len(arr)
      for i in range(2, length):
            if arr - arr != diff:
                return False
      return True
页: [1]
查看完整版本: 【朱迪的LeetCode刷题笔记】1502. Can Make Arithmetic Progression From Sequence