LeetCode—1502

Approach

# 排序後再確認是否符合等差級數
Sort and then verify whether the elements form a valid arithmetic progression.

Time Complexity

# n = length of vector
O(nlogn)

Space Complexity

# n = length of vector
O(n)

Code

class Solution {
public:
    bool canMakeArithmeticProgression(vector<int>& arr) {
        sort(arr.begin(), arr.end());

        int l = arr.size();

        for (int i = 2 ; i < l ; i++) {
            if (arr[i] - arr[i - 1] != arr[1] - arr[0]) {
                return false;
            }
        }

        return true;
    }
};