題目
給定一個整數(shù)類型的數(shù)組 nums崇堰,請編寫一個能夠返回數(shù)組“中心索引”的方法升熊。
我們是這樣定義數(shù)組中心索引的:數(shù)組中心索引的左側(cè)所有元素相加的和等于右側(cè)所有元素相加的和俄烁。
如果數(shù)組不存在中心索引,那么我們應(yīng)該返回 -1级野。如果數(shù)組有多個中心索引页屠,那么我們應(yīng)該返回最靠近左邊的那一個。
示例 1:
輸入:
nums = [1, 7, 3, 6, 5, 6]
輸出: 3
解釋:
索引3 (nums[3] = 6) 的左側(cè)數(shù)之和(1 + 7 + 3 = 11)蓖柔,與右側(cè)數(shù)之和(5 + 6 = 11)相等辰企。
同時, 3 也是第一個符合要求的中心索引。
示例 2:
輸入:
nums = [1, 2, 3]
輸出: -1
解釋:
數(shù)組中不存在滿足此條件的中心索引况鸣。
說明:
nums 的長度范圍為 [0, 10000]牢贸。
任何一個 nums[i] 將會是一個范圍在 [-1000, 1000]的整數(shù)。
C++解法
#include <iostream>
#include <vector>
#include <map>
#include <set>
using namespace std;
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum = 0, n = 0;
for (int i = 0; i < nums.size(); ++i) sum += nums[i];
for (int i = 0; i < nums.size(); ++i) {
if (sum - nums[i] == n * 2) return i;
n += nums[i];
}
return -1;
}
};
int main(int argc, const char * argv[]) {
Solution solution;
vector<int> vec {1, 7, 3, 6, 5, 6};
cout << solution.pivotIndex(vec) << endl;
vec = {1, 2, 3};
cout << solution.pivotIndex(vec) << endl;
vec = {-1,-1,-1,-1,-1,-1};
cout << solution.pivotIndex(vec) << endl;
vec = {-1,-1,-1,-1,-1,0};
cout << solution.pivotIndex(vec) << endl;
return 0;
}
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-pivot-index