首页 > 其他分享 >[Leetcode] 0724. 寻找数组的中心下标

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

时间:2023-06-21 15:13:03浏览次数:65  
标签:下标 0724 nums int sum 数组 Leetcode left

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 的长度。

相似题目:

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;
    }
};

标签:下标,0724,nums,int,sum,数组,Leetcode,left
From: https://www.cnblogs.com/yege/p/17496250.html

相关文章

  • [Leetcode] 0728. 自除数
    728.自除数点击上方,跳转至leetcode题目描述自除数 是指可以被它包含的每一位数整除的数。例如,128是一个自除数,因为 128%1==0,128%2==0,128%8==0。自除数不允许包含0。给定两个整数 left 和 right,返回一个列表,列表的元素是范围 [left,right] 内......
  • [Leetcode] 0733. 图像渲染
    733.图像渲染点击上方,跳转至leetcode题目描述有一幅以 mxn 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。你也被给予三个整数sr, sc和newColor。你应该从像素 image[sr][sc] 开始对图像进行上色填充。为了完成上色工作,从......
  • [Leetcode] 0709. 转换成小写字母
    709.转换成小写字母点击上方跳转至Leetcode题目描述给你一个字符串s,将该字符串中的大写字母转换成相同的小写字母,返回新的字符串。 示例1:输入:s="Hello"输出:"hello"示例2:输入:s="here"输出:"here"示例3:输入:s="LOVELY"输出:"lovely" 提示:1<=s.l......
  • [Leetcode] 0717. 1 比特与 2 比特字符
    717.1比特与2比特字符点击上方,跳转至leetcode题目描述有两种特殊字符:第一种字符可以用一比特 0表示第二种字符可以用两比特(10 或 11)表示给你一个以0结尾的二进制数组 bits ,如果最后一个字符必须是一个一比特字符,则返回true。 示例 1:输入:bits=[1,......
  • [Leetcode] 0706. 设计哈希映射
    706.设计哈希映射点击跳转至leetcode题目描述不使用任何内建的哈希表库设计一个哈希映射(HashMap)。实现MyHashMap类:MyHashMap()用空映射初始化对象voidput(intkey,intvalue)向HashMap插入一个键值对(key,value)。如果key已经存在于映射中,则更新其对应的值v......
  • [LeetCode] 2090. K Radius Subarray Averages
    Youaregivena 0-indexed array nums of n integers,andaninteger k.The k-radiusaverage forasubarrayof nums centered atsomeindex i withthe radius k istheaverageof all elementsin nums betweentheindices i-k and i+k (i......
  • 每日一题力扣 1262 https://leetcode.cn/problems/greatest-sum-divisible-by-three/
    、 题解这道题目核心就算是要知道如果x%3=2的话,应该要去拿%3=1的数字,这样子才能满足%3=0贪心sum不够%3的时候,就减去余数为1的或者余数为2的需要注意两个余数为1会变成余数为2的,所以可能减去2个余数为1核心代码如下publicintmaxSumDivThreeOther(int[]nums){​  ......
  • LeetCode 周赛 350(2023/06/18)01 背包变型题
    本文已收录到AndroidFamily,技术和职场问题,请关注公众号[彭旭锐]和[BaguTreePro]知识星球提问。往期回顾:LeetCode单周赛第348场·数位DP模版学会了吗?T1.总行驶距离(Easy)标签:模拟T2.找出分区值(Medium)标签:排序T3.特别的排列(Medium)标签:图、状态压缩、......
  • Leetcode Hot 100 & 239. Sliding Window Maximum
    参考资料:Python文档heapq部分考点:子串&[题干]1Input:nums=[1,3,-1,-3,5,3,6,7],k=32Output:[3,3,5,5,6,7]3Explanation:4WindowpositionMax5--------------------6[13-1]-353673......
  • C# 获取数组排序后的下标
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceConsoleApp9{classProgram{staticvoidMain(string[]args){int[]src=newint[]{2,1......