1502. Determine whether an arithmetic sequence can be formed (C++)
1 topic description
Give you a numeric array arr.
If the difference between any two adjacent items in a sequence is always equal to the same constant, then the sequence is called an arithmetic sequence.
If you can rearrange the array to form an arithmetic sequence, please return true; otherwise, return false.
2 Example description
2.1 Example 1
Input: arr = [3,5,1]
Output: true
Explanation: Reorder the array to get [1,3,5] or [5,3,1], the difference between any two adjacent items is 2 or -2 respectively , Can form an arithmetic sequence.
2.2 Example 2
Input: arr = [1,2,4]
Output: false
Explanation: The arithmetic sequence cannot be obtained by reordering.
3 Problem solving tips
2 <= arr.length <= 1000
-10^6 <= arr[i] <= 10^6
4 Problem-solving ideas
According to the formula of arithmetic sequence, the middle term = the previous term + the next term; it can be solved.
5 Detailed source code (C++)
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
sort( arr.begin() , arr.end() );
for ( int i = 0 ; i < arr.size() - 2 ; i ++ )
{
if ( arr[i+1] * 2 != arr[i] + arr[i+2] )
{
return false ;
}
}
return true ;
}
};