[Leetcode] 0724. 寻找数组的中心下标

news/2024/7/20 17:40:23 标签: leetcode, 算法, 华为od, 职场和发展

724. 寻找数组的中心下标

点击上方,跳转至leetcode

题目描述

给你一个整数数组 nums ,请计算数组的 中心下标

数组 中心下标 是数组的一个下标,其左侧所有元素相加的和等于右侧所有元素相加的和。

如果中心下标位于数组最左端,那么左侧数之和视为 0 ,因为在下标的左侧不存在元素。这一点对于中心下标位于数组最右端同样适用。

如果数组有多个中心下标,应该返回 最靠近左边 的那一个。如果数组不存在中心下标,返回 -1

示例 1:

输入:nums = [1, 7, 3, 6, 5, 6]
输出:3
解释:
中心下标是 3 。
左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,
右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。

示例 2:

输入:nums = [1, 2, 3]
输出:-1
解释:
数组中不存在满足此条件的中心下标。

示例 3:

输入:nums = [2, 1, -1]
输出:0
解释:
中心下标是 0 。
左侧数之和 sum = 0 ,(下标 0 左侧不存在元素),
右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。

提示:

  • 1 <= nums.length <= 104
  • -1000 <= nums[i] <= 1000

注意:本题与主站 1991 题相同:https://leetcode.cn/problems/find-the-middle-index-in-array/

解法一

方法一:前缀和

记数组的全部元素之和为 \(total\),当遍历到第 \(i\) 个元素时,设其左侧元素之和为 \(sum\),则其右侧元素之和为\(total−nums_i−sum\)。左右侧元素相等即为 \(sum=total−nums_i−sum\),即 \(2×sum+nums_i=total\)
当中心索引左侧或右侧没有元素时,即为零个项相加,这在数学上称作「空和」(empty sum)。在程序设计中我们约定「空和是零」。

时间复杂度:\(O(n)\),其中 \(n\)为数组的长度。

空间复杂度:\(O(1)\)

Python3

from typing import List

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        total  = sum(nums)
        left = 0
        for i in range(len(nums)):
            if (2 * left + nums[i]) == total:
                return i
            left += nums[i]
        return -1

# nums = [1, 7, 3, 6, 5, 6]
# nums = [1, 2, 3]
nums = [2, 1, -1]
res = Solution().pivotIndex(nums)
print(res)

C++

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;


class Solution {
public:
    int pivotIndex(vector<int> &nums) {
        int total = accumulate(nums.begin(), nums.end(), 0);
        int left = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (2 * left + nums[i] == total) {
                return i;
            }
            left += nums[i];
        }
        return -1;
    }
};

int main(){

    vector<int> nums = {1, 7, 3, 6, 5, 6};
    // vector<int> nums = {1, 2, 3};
    // vector<int> nums = {2, 1, -1};
    int res = Solution().pivotIndex(nums);
    cout << res << endl;
    return 0;
}

//g++ 724.cpp -std=c++11

解法二

方法二:前缀和

我们定义变量 \(left\) 表示数组 nums 中下标 \(i\) 左侧元素之和,变量 \(right\) 表示数组 nums 中下标 \(i\) 右侧元素之和。初始时 \(left = 0\), \(right = \sum_{i = 0}^{n - 1} nums[i]\)

遍历数组 nums,对于当前遍历到的数字 \(x\),我们更新 \(right = right - x\),此时如果 \(left=right\),说明当前下标 \(i\) 就是中间位置,直接返回即可。否则,我们更新 \(left = left + x\),继续遍历下一个数字。

遍历结束,如果没有找到中间位置,返回 \(-1\)

时间复杂度 \(O(n)\),空间复杂度 \(O(1)\)。其中 \(n\) 为数组 nums 的长度。

相似题目:

  • 1991. 找到数组的中间位置
  • 2574. 左右元素和的差值

Python3

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        left, right = 0, sum(nums)
        for i, x in enumerate(nums):
            right -= x
            if left == right:
                return i
            left += x
        return -1

C++

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        int left = 0, right = accumulate(nums.begin(), nums.end(), 0);
        for (int i = 0; i < nums.size(); ++i) {
            right -= nums[i];
            if (left == right) {
                return i;
            }
            left += nums[i];
        }
        return -1;
    }
};

http://www.niftyadmin.cn/n/459308.html

相关文章

一文理解多线程机制和多线程的优缺点

一文理解多线程机制 前言&#xff1a;多线程的优缺点。一、什么是多线程1.1、多线程的概念和基本原理1.2、多线程与单线程的区别 二、多线程的应用场景三、C 中的多线程3.1、C11 新增加的 thread 库3.2、C 线程同步机制&#xff08;mutex、condition_variable&#xff09; 四.、…

在Ubuntu系统上安装Rocket.Chat并启用HTTPS的完整教程

更新系统软件包列表&#xff1a; sudo apt update安装Node.js和npm&#xff1a; sudo apt install -y nodejs npm安装MongoDB数据库&#xff1a; sudo apt install -y mongodb启动MongoDB服务&#xff1a; sudo systemctl start mongodb下载Rocket.Chat的最新版本&…

Redis原理 - Redis网络模型

原文首更地址&#xff0c;阅读效果更佳&#xff01; Redis原理 - Redis网络模型 | CoderMast编程桅杆https://www.codermast.com/database/redis/redis-netword-model.html 思考 Redis 到底是单线程还是多线程&#xff1f; 如果仅仅针对 Redis 的核心业务部分&#xff08;命…

京东四面面经整理

内容摘自我的学习网站&#xff1a;topjavaer.cn 一面 kafka在应用场景以及 项目 里的实现bitmap底层object里有哪些方法hashmap相关sychronized和reentrantlock相关问题以及锁升级cas和volatile线程几种状态以及转化jvm内存模型mybatis相关问题Redis数据结构&#xff0c;问了下…

本论文以图像识别为研究对象,采用数学建模方法,探索图像识别中的问题并提出解决方案。

第一部分&#xff1a;问题描述 随着数字图像的广泛应用&#xff0c;图像识别技术逐渐成为热门研究领域。但是&#xff0c;在实际应用中&#xff0c;由于图像的复杂性和噪声的存在&#xff0c;图像识别的准确性和效率仍然存在一定的挑战。因此&#xff0c;本论文旨在研究图像识…

Arthas原理分析

在日常开发中&#xff0c;经常会使用到arthas排查线上问题&#xff0c;觉得arthas的功能非常强大&#xff0c;所以打算花了点时间了解一下其实现原理。并试着回答一下使用Arthas时存在的一些疑问。 Arthas主要基于是Instrumentation JavaAgent Attach API ASM 反射 OGNL等…

【青书学堂】作业-大学英语Ⅰ(高起专)

【青书学堂】作业-大学英语Ⅰ(高起专) 第1题 单选题 Our father often told us in the past that _____ is believing.( )。 选项: A: to see B: seeing C: see D: to be 答案:B 第2题 单选题 –I don’t know whether to take up law or medicine.–________.。 选项…

2022(一等奖)D1073基于Himawari-8卫星遥感的黑龙江省地表水时空格局研究

作品介绍 1 项目简介 为探究黑龙江省地表水空间格局变化&#xff0c;本项目以黑龙江省为例&#xff0c;基于高时相Himawari-8号卫星数据&#xff0c;通过影像预处理、特征指数选择、自动阈值分类、集成学习和随机森林分类等步骤&#xff0c;融合IDL二次开发与GIS空间分析&…