Skip to content

Latest commit

 

History

History

1502

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Related Topics:
Array, Sort

Solution 1.

// OJ: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& A) {
        sort(begin(A), end(A));
        int d = A[1] - A[0];
        for (int i = 2; i < A.size(); ++i) {
            if (A[i] - A[i - 1] != d) return false;
        }
        return true;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
// Ref: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720152/O(n)-time-O(1)-space
class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& A) {
        int mn = *min_element(begin(A), end(A)), mx = *max_element(begin(A), end(A)), N = A.size();
        if ((mx - mn) % (N - 1)) return false;
        int d = (mx - mn) / (N - 1);
        for (int i = 0; i < N;) {
            if (A[i] == mn + i * d) ++i;
            else if ((A[i] - mn) % d) return false;
            else {
                int j = (A[i] - mn) / d;
                if (j < i || A[i] == A[j]) return false;
                swap(A[i], A[j]);
            }
        }
        return true;
    }
};