Leetcode 724—— Find Pivot Index(寻找数组的中心索引)

博客分类: Leetcode 刷题笔记 阅读次数: 102 次

Leetcode 724—— Find Pivot Index(寻找数组的中心索引)

题目描述

Example 1:
Input: 
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation: 
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input: 
nums = [1, 2, 3]
Output: -1
Explanation: 
There is no index that satisfies the conditions in the problem statement.
Note:

解题思路

此题目要求我们找出数组的 中心索引 ,也就是说,数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。

参考代码

示例代码一
//C++
class Solution {
public:
	int pivotIndex(vector<int>& nums)
	{
		int Lsum, Rsum;
		int count = nums.size();
		for (int i = 0; i < count; i++)
		{
			Lsum = Rsum = 0;
			for (int j = 0; j < i; j++)
			{
				Lsum += nums[j];
			}
			for (int j = i + 1; j < count; j++)
			{
				Rsum += nums[j];
			}
			if (Lsum == Rsum)
				return i;
		}
		return -1;
	}
};
示例代码二
//C++
class Solution {
public:
	int pivotIndex(vector<int>& nums)
	{
		int Lsum = 0, Rsum = accumulate(nums.begin(),nums.end(),0);
		int count = nums.size();
		for (int i = 0; i < count; i++)
		{
			Rsum -= nums[i];

			if (Lsum == Rsum)
				return i;

			Lsum += nums[i];
		}
		return -1;
	}
};