724.寻找数组的中心下标
链接:724.寻找数组的中心下标
难度:Easy
标签:数组、前缀和
简介:给定一个整数类型的数组 nums,请编写一个能够返回数组 “中心索引” 的方法。
题解 1 - python
- 编辑时间:2024-07-08
- 执行用时:54ms
- 内存消耗:17.25MB
- 编程语言:python
- 解法介绍:遍历。
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
l = 0
r = sum(nums)
for i in range(len(nums)):
r -= nums[i]
if l == r: return i
l += nums[i]
return -1
题解 2 - typescript
- 编辑时间:2021-01-28
- 执行用时:120ms
- 内存消耗:41.1MB
- 编程语言:typescript
- 解法介绍:前缀和。
function pivotIndex(nums: number[]): number {
const sum = nums.reduce((total, cur) => total + cur, 0);
const len = nums.length;
let l = 0;
for (let i = 0; i < len; i++) {
if (l === sum - l - nums[i]) return i;
l += nums[i];
}
return -1;
}
题解 3 - cpp
- 编辑时间:2021-12-23
- 执行用时:24ms
- 内存消耗:30.2MB
- 编程语言:cpp
- 解法介绍:前缀和。
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum = 0;
for (auto& num : nums) sum += num;
int pre = 0;
for (int i = 0; i < nums.size(); i++) {
if (sum - nums[i] == pre) return i;
pre += nums[i];
sum -= nums[i];
}
return -1;
}
};