判断能否形成等差数列 - 简单
*************
C++
topic: 1502. 判断能否形成等差数列 - 力扣(LeetCode)
*************
Have a slight inspect at the topic.
![]() |
Sort first when I give the topic first eye. Sort is a standard library in c++. This basic use of sort is really easy.
int arr[] = {4, 2, 5, 1};
sort(arr.begin(), arr.end()); // 结果:{1, 2, 4, 5}
vector<int> vec = {4, 2, 5, 1};
sort(vec.begin(), vec.end()); // 结果:{1, 2, 4, 5}
Sort by default ranks from small to big. If you want to range the elements from big to small, do something.
// 降序排序
sort(vec.begin(), vec.end(), greater<int>());
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr) {
// sort the vector first
sort(arr.begin(), arr.end());
int n = arr.size();
// calculater the difference
int a = arr[1] - arr[0];
for (int i = 1; i < n; ++i)
{
if (arr[i] - arr[i - 1] == a)
{
return true;
}
else
{
}
}
return false;
}
};
But you gays guess what.
![]() |
I dont know where is wrong. Run the program manually.
步骤 | 当前执行代码行 | 变量状态变化 | 条件判断结果 | 循环迭代次数 | 输出内容 | 操作注释 |
---|---|---|---|---|---|---|
1 | sort(arr.begin(), arr.end()); | arr → <span style=‘color:red’>[1,2,4]</span> | 无 | 无 | 无 | 对数组进行升序排序 |
2 | int n = arr.size(); | n → <span style=‘color:red’>3</span> | 无 | 无 | 无 | 获取数组长度 |
3 | int a = arr[1] - arr[0]; | a → <span style=‘color:red’>1</span> | 无 | 无 | 无 | 计算初始差值(假设为公差) |
4 | for (int i = 1; i < n; ++i) | i → <span style=‘color:red’>1</span> | i < 3 → true | 第1次迭代 | 无 | 进入循环,检查公差一致性 |
5 | if (arr[i] - arr[i-1] == a) | 无 | 条件成立 | 无 | 无 | 差值等于初始公差 a=1 |
6 | return true; | 无 | 无 | 无 | true | 立即返回 true ,函数终止 |
OK, that make sense.
class Solution {
public:
bool canMakeArithmeticProgression(vector<int>& arr)
{
sort(arr.begin(), arr.end());
int n = arr.size();
int diff = arr[1] - arr[0]; // 记录标准差值
// 从第2个元素开始检查所有相邻对
for (int i = 2; i < n; ++i)
{ // 注意i从2开始
if (arr[i] - arr[i-1] != diff)
{
return false;
}
}
return true; // 全部符合条件
}
};