Find Pivot Index

Given an array of integers nums, write a method that returns the "pivot" index of this array.

We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.

If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most 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:

  • The length of nums will be in the range [0, 10000].
  • Each element nums[i] will be an integer in the range [-1000, 1000].

找到一个支点,左右两边的值的和相等,求这个指点的index,思路:和减去支点,左右两边是否相等,也就是,2倍关系

 1 class Solution {
 2 public:
 3     int pivotIndex(vector<int>& nums) {
 4         if(nums.empty())
 5             return -1;
 6         
 7         int sum = accumulate(nums.begin(), nums.end(), 0);
 8         
 9         if(sum - nums[0] == 0)
10         {
11             return 0;
12         }
13         
14         int n =nums.size();
15         int x = 0;
16         for(int i = 1; i < n; ++i)
17         {
18             x += nums[i - 1];
19             
20             if(sum - nums[i] == 2 * x)
21             {
22                 return i;
23             }
24             
25         }
26         
27         return -1;
28     }
29 };

 

posted @ 2018-03-22 20:48  还是说得清点吧  阅读(174)  评论(0编辑  收藏  举报