Leetcode 724: Find Pivot Index (前缀和数组简单题)

  1. Find Pivot Index
    Easy

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

Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/

解法1:前缀和数组

cpp 复制代码
class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int n = nums.size();
        vector<int> presums(n + 1, 0);
        for (int i = 1; i <= n; i++) presums[i] = presums[i - 1] + nums[i - 1];
        
        for (int i = 1; i <= n; i++) {
            if (presums[i - 1] == presums[n] - presums[i]) return i - 1;
        }
        return -1;
    } 
};
相关推荐
青少儿编程课堂33 分钟前
图形化编程实战:智能交通灯调度台,一个作品讲透循环、条件与广播
c++·python·算法·bfs·信息学竞赛
evans在进步37 分钟前
LeetCode 438 找到字符串中所有字母异位词:滑动窗口与排序解法详解
算法·leetcode·职场和发展
M78佐菲41 分钟前
Linux多线程:创建、回收与互斥同步
linux·笔记·学习·算法
小手cool1 小时前
使用递归对数组进行反转操作
java·数据结构·算法
兔兔兔兔11 小时前
记录C++ 13
开发语言·c++·算法
码行山野赴时序归途1 小时前
从暴力到最优:三道 C 语言入门题的解法思路
c语言·开发语言·数据结构·算法·leetcode·排序算法
土司大王1 小时前
LeetCode hot100——随机链表的复制
算法·leetcode·链表
叠层归一研究院1 小时前
螺旋时空:E框架的整合宇宙论
人工智能·经验分享·算法·机器学习·agi
磁场转动100万匹1 小时前
线性回归算法实现训练数据集、测试数据集的缺失值填充
算法·机器学习·线性回归
乐迪信息2 小时前
防爆AI摄像机实时监测船舶异常姿态
大数据·人工智能·算法·安全·目标跟踪