判断能否形成等差数列 - 简单

*************

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.

步骤当前执行代码行变量状态变化条件判断结果循环迭代次数输出内容操作注释
1sort(arr.begin(), arr.end());arr → <span style=‘color:red’>[1,2,4]</span>对数组进行升序排序
2int n = arr.size();n → <span style=‘color:red’>3</span>获取数组长度
3int a = arr[1] - arr[0];a → <span style=‘color:red’>1</span>计算初始差值(假设为公差)
4for (int i = 1; i < n; ++i)i → <span style=‘color:red’>1</span>i < 3 → true第1次迭代进入循环,检查公差一致性
5if (arr[i] - arr[i-1] == a)条件成立差值等于初始公差 a=1
6return 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; // 全部符合条件
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值