博客
关于我
LeetCode 724 寻找数组的中心索引 HERODING的LeetCode之路
阅读量:192 次
发布时间:2019-02-28

本文共 827 字,大约阅读时间需要 2 分钟。

为了解决这个问题,我们需要找到数组的“中心索引”。中心索引的定义是左侧所有元素的和等于右侧所有元素的和。如果有多个满足条件的索引,返回最靠近左边的那个。如果不存在这样的索引,返回-1。

方法思路

  • 计算总和:首先计算整个数组所有元素的总和。
  • 遍历数组:从左到右遍历数组,逐步累加左侧元素的和。
  • 检查条件:在每一步检查左侧和当前元素的和是否等于总和。如果是,返回当前索引。
  • 返回结果:如果遍历完数组后没有找到满足条件的索引,返回-1。
  • 这种方法的时间复杂度是O(n),其中n是数组的长度。我们先计算总和,然后再遍历一次数组,确保在最优时间复杂度内解决问题。

    解决代码

    #include 
    #include
    // for accumulateusing namespace std;int pivotIndex(vector
    & nums) { int sum_total = accumulate(nums.begin(), nums.end(), 0); int sum_left = 0; for (int i = 0; i < nums.size(); ++i) { if (2 * sum_left + nums[i] == sum_total) { return i; } sum_left += nums[i]; } return -1;}

    代码解释

  • 计算总和:使用accumulate函数计算数组所有元素的总和。
  • 遍历数组:从左到右遍历数组,逐步累加左侧元素的和。
  • 检查条件:在每一步检查左侧和当前元素的和是否等于总和。如果是,返回当前索引。
  • 返回结果:如果遍历完数组后没有找到满足条件的索引,返回-1。
  • 这种方法确保了在最优时间复杂度内找到中心索引,适用于大数组的情况。

    转载地址:http://ntkj.baihongyu.com/

    你可能感兴趣的文章
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm切换到淘宝源
    查看>>
    npm前端包管理工具简介---npm工作笔记001
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    NPOI之Excel——合并单元格、设置样式、输入公式
    查看>>
    NPOI利用多任务模式分批写入多个Excel
    查看>>
    NR,NF,FNR
    查看>>
    nrf开发笔记一开发软件
    查看>>
    NSDateFormatter的替代方法
    查看>>
    nsis 安装脚本示例(转)
    查看>>
    NSOperation基本操作
    查看>>