LeetCode75——Day19

文章目录

一、题目

724. Find Pivot Index

Given an array of integers nums, calculate the pivot index of this array.

The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.

If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.

Return the leftmost pivot index. If no such index exists, return -1.

Example 1:

Input: nums = 1,7,3,6,5,6

Output: 3

Explanation:

The pivot index is 3.

Left sum = nums0 + nums1 + nums2 = 1 + 7 + 3 = 11

Right sum = nums4 + nums5 = 5 + 6 = 11

Example 2:

Input: nums = 1,2,3

Output: -1

Explanation:

There is no index that satisfies the conditions in the problem statement.

Example 3:

Input: nums = 2,1,-1

Output: 0

Explanation:

The pivot index is 0.

Left sum = 0 (no elements to the left of index 0)

Right sum = nums1 + nums2 = 1 + -1 = 0

Constraints:

1 <= nums.length <= 104

-1000 <= numsi <= 1000

二、题解

利用前缀和的思想做题

cpp 复制代码
class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int n = nums.size();
        vector<int> prefixSum(n+1,0);
        for(int i = 1;i <= n;i++){
            prefixSum[i] = prefixSum[i-1] + nums[i-1];
        }
        for(int i = 0;i < n;i++){
            int left = prefixSum[i];
            int right = prefixSum[n] - prefixSum[i + 1];
            if(left == right) return i;
        }
        return -1;
    }
};
相关推荐
一拳一个呆瓜1 小时前
【STL】iostream 编程:检测提取操作产生的错误
c++·stl
稚南城才子,乌衣巷风流1 小时前
判断素数与拓展应用
c++
众少成多积小致巨1 小时前
C++ 规范参考(下)
c++
c238561 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
aaaameliaaa2 小时前
指针之总结
c语言·笔记·算法
宵时待雨3 小时前
优选算法专题9:哈希表
数据结构·算法·散列表
txzrxz3 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
gwf2163 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
noipp3 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu
c238563 小时前
C/C++每日一练6
c语言·c++·算法