-
Notifications
You must be signed in to change notification settings - Fork 0
/
1502. Can Make Arithmetic Progression From Sequence.cpp
56 lines (48 loc) · 1.35 KB
/
1502. Can Make Arithmetic Progression From Sequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
int n = arr.size();
int minNumber = INT_MAX;
int maxNumber = INT_MIN;
for (int num : arr) {
if (minNumber > num)
minNumber = num;
if (maxNumber < num)
maxNumber = num;
}
if ((maxNumber - minNumber) % (n - 1) != 0)
return false;
int difference = (maxNumber - minNumber) / (n - 1);
int i = 0;
while (i < n) {
if (arr[i] == minNumber + difference * i)
i++;
else if ((arr[i] - minNumber) % difference != 0)
return false;
else {
int pos = (arr[i] - minNumber) / difference;
if (pos < i || arr[pos] == arr[i])
return false;
int tmp = arr[pos];
arr[pos] = arr[i];
arr[i] = tmp;
}
}
return true;
}
};
//2nd sol
class Solution {
public:
bool isArithmeticProgression(vector<int>& arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
int diff = arr[1] - arr[0];
for(int i = 2; i < n; i++){
if((arr[i] - arr[i - 1]) != diff){
return false;
}
}
return true;
}
};