2

#yyds干货盘点# leetcode算法题:寻找数组的中心下标

 2 years ago
source link: https://blog.51cto.com/u_13321676/5515603
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# leetcode算法题:寻找数组的中心下标

原创

灰太狼_cxh 2022-07-26 16:34:08 博主文章分类:leetcode ©著作权

文章标签 数组 代码实现 文章分类 Java 编程语言 阅读数143

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

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

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

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

输入:nums = [1, 7, 3, 6, 5, 6]

中心下标是 3 。

左侧数之和 sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 ,

右侧数之和 sum = nums[4] + nums[5] = 5 + 6 = 11 ,二者相等。

输入:nums = [1, 2, 3]

输出:-1

数组中不存在满足此条件的中心下标。

输入:nums = [2, 1, -1]

中心下标是 0 。

左侧数之和 sum = 0 ,(下标 0 左侧不存在元素),

右侧数之和 sum = nums[1] + nums[2] = 1 + -1 = 0 。

代码实现:

class Solution {
public int pivotIndex(int[] nums) {
int total = Arrays.stream(nums).sum();
int sum = 0;
for (int i = 0; i < nums.length; ++i) {
if (2 * sum + nums[i] == total) {
return i;
}
sum += nums[i];
}
return -1;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK