当前位置: 首页 > news >正文

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

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

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; // 全部符合条件
    }
};

相关文章:

  • P9241 [蓝桥杯 2023 省 B] 飞机降落
  • 第44天:WEB攻防-PHP应用SQL盲注布尔回显延时判断报错处理增删改查方式
  • SpaceSync智能排班:重构未来办公空间的神经中枢
  • AI对前端开发的冲击
  • msf(Metasploit)中Session与Channel的区别与关系解析
  • 微信小程序项目 tabBar 配置问题:“pages/mine/mine“ need in [“pages“]
  • 计算机硬件与体系结构
  • set_max_delay
  • 康谋应用 | 基于多传感器融合的海洋数据采集系统
  • ROS动态调参
  • 【论文阅读】LightTS:少即是多:基于轻采样的MLP结构的快速多元时间序列预测
  • 信号处理之插值、抽取与多项滤波
  • 第16届计算智能与软件工程国际研讨会(CISE 2026)
  • MAC地址
  • 【设计模式】从事件驱动到即时更新:掌握观察者模式的核心技巧
  • 【MySQL】基本操作 —— DDL
  • C#枚举(Enum)详解
  • 10✨让笔迹突破语言壁垒!Manus AI 多语言识别开启智能书写新纪元
  • CMD批处理一些冷门命令,编写windows脚本常用?
  • vue3+setup组件封装及传值
  • 今晚油价下调,加满一箱油将省9元
  • 南宁海关辟谣网传“查获600公斤稀土材料”:实为焊锡膏
  • 国家统计局:消费对我国经济增长的拉动有望持续增长
  • 国家统计局:1-4月份,全国固定资产投资同比增长4.0%
  • 体育文化赋能国际交流,上海黄浦举办国际友人城市定向赛
  • 上海这场有温度的“人才集市”,为更多人才搭建“暖心桥”