LeetCode C++ 724. Find Pivot Index【Array/前缀和】简单
发布日期:2021-07-01 02:49:55
浏览次数:2
分类:技术文章
本文共 2102 字,大约阅读时间需要 7 分钟。
Given an array of integers nums
, write a method that returns the “pivot” index of this array.
We define the pivot index as the index where the sum of all the numbers to the left of the index is equal to the sum of all the numbers to the right of the index.
If no such index exists, we should return -1
. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input: nums = [1,7,3,6,5,6]Output: 3Explanation:The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.Also, 3 is the first index where this occurs.
Example 2:
Input: nums = [1,2,3]Output: -1Explanation:There is no index that satisfies the conditions in the problem statement.
Constraints:
- The length of nums will be in the range
[0, 10000]
. - Each element nums[i] will be an integer in the range
[-1000, 1000]
.
题意:判断数组中是否存在枢纽元,即该索引的左侧所有元素相加的和等于右侧所有元素相加的和。
思路:前缀和。我们求出前缀和数组,左侧所有元素的和等于 presum[i]
,右侧所有元素的和等于 presum[n] - presum[i + 1]
,判断是否相等即可。
代码如下:
class Solution { public: int pivotIndex(vector & nums) { if (nums.empty()) return -1; if (nums.size() == 1) return 0; int n = nums.size(), presum[n + 1]; presum[0] = 0; for (int i = 0; i < n; ++i) presum[i + 1] = presum[i] + nums[i]; for (int i = 0; i < n; ++i) { int leftSum = presum[i], rightSum = presum[n] - presum[i + 1]; if (leftSum == rightSum) return i; } return -1; }};
这里可以优化一下,不使用前缀和数组,节省一点空间:
class Solution { public: int pivotIndex(vector & nums) { if (nums.empty()) return -1; if (nums.size() == 1) return 0; int n = nums.size(), presum = 0, total = 0; for (int i = 0; i < n; ++i) total += nums[i]; for (int i = 0; i < n; ++i) { if (presum * 2 + nums[i] == total) //presum == total - presum - nums[i] return i; presum += nums[i]; } return -1; }};
效率:
执行用时:52 ms, 在所有 C++ 提交中击败了74.21% 的用户内存消耗:31.1 MB, 在所有 C++ 提交中击败了50.29% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108120843 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月30日 00时20分50秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
spark 笔记1
2019-05-01
shell dirname basename
2019-05-01
未来已至,5G加持下的云游戏将走向何方?
2019-05-01
计算机网络 —— 网络层 1.
2019-05-01
Android 之 ContentProvider 与 ContentResolver
2019-05-01
【接口自动化】
2019-05-01
Python解惑之:True与False
2019-05-01
你要的微信小程序终于来了
2019-05-01
有了这些 Chrome 插件,效率提升10倍(建议收藏)
2019-05-01
只有1%的程序员搞懂过浮点数陷阱
2019-05-01
一名 Google 工程师的大数据处理经验
2019-05-01
命名难,难于上青天
2019-05-01
没钱没公司,怎么做一款付费产品
2019-05-01
代码整洁之道-编写 Pythonic 代码
2019-05-01
树莓派程序开机自启动
2019-05-01
连锁门店无线通信方案
2019-05-01
配置Lotus Domino集群视频详解
2019-05-01
Linux软件万花筒
2019-05-01
全球开源软件发展趋势分析
2019-05-01