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;
    }
};
相关推荐
别动哪条鱼2 小时前
AAC ADTS 帧结构信息
网络·数据结构·ffmpeg·音视频·aac
艾莉丝努力练剑2 小时前
【C++:异常】C++ 异常处理完全指南:从理论到实践,深入理解栈展开与最佳实践
java·开发语言·c++·安全·c++11
Zsy_0510038 小时前
【数据结构】二叉树OJ
数据结构
快乐zbc8 小时前
【C++ 基础】:给定一个指针 p,你能判断它是否指向合法的对象吗?
c++
sulikey8 小时前
C++类和对象(下):初始化列表、static、友元、内部类等核心特性详解
c++·static·初始化列表·友元·匿名对象·内部类·编译器优化
oioihoii9 小时前
C++网络编程:从Socket混乱到优雅Reactor的蜕变之路
开发语言·网络·c++
程序员东岸10 小时前
《数据结构——排序(中)》选择与交换的艺术:从直接选择到堆排序的性能跃迁
数据结构·笔记·算法·leetcode·排序算法
程序员-King.10 小时前
day104—对向双指针—接雨水(LeetCode-42)
算法·贪心算法
笨鸟要努力10 小时前
Qt C++ windows 设置系统时间
c++·windows·qt