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 = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11

Right sum = nums[4] + nums[5] = 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 = nums[1] + nums[2] = 1 + -1 = 0

Constraints:

1 <= nums.length <= 104

-1000 <= nums[i] <= 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;
    }
};
相关推荐
梯度下降中7 分钟前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy11 分钟前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl2002092512 分钟前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
第二只羽毛39 分钟前
C++ 高并发内存池1
大数据·开发语言·c++·开源
不想看见4041 小时前
C++/Qt 实习岗位深度解析【结合一次研发实习谈感受】
开发语言·c++·qt
靴子学长1 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
王老师青少年编程1 小时前
信奥赛C++提高组csp-s之组合数学专题课:鸽巢原理详解及案例实践
c++·组合数学·信奥赛·抽屉原理·csp-s·提高组·鸽巢原理
寒秋花开曾相惜1 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才1 小时前
2026年计算机领域的年度主题与范式转移
算法
njidf2 小时前
C++与Qt图形开发
开发语言·c++·算法