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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public: bool canMakeArithmeticProgression(vector<int>& arr) { int mi = INT_MAX, ma = INT_MIN; unordered_set<int> s; for(auto n : arr) { mi = min(mi, n); ma = max(ma, n); s.insert(n); } int diff = (ma - mi) / (arr.size() - 1); while(mi != ma) { if(!s.count(mi + diff)) return false; mi += diff; } return true; } };
|
- Time : O(nlogn)
- Space : O(1)
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: bool canMakeArithmeticProgression(vector<int>& arr) { sort(arr.begin(), arr.end()); int diff = arr[0] - arr[1]; for(int i = 1; i < arr.size() - 1; i++) { if(arr[i] - arr[i+1] != diff) return false; } return true; } };
|