//解法一:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int index = 0,flag = 0;
nums.push_back(0);
vector<int>::iterator it = nums.begin();
vector<int>::iterator tmp = it++;
while(it != nums.end())
{
tmp = it;
if(accumulate(nums.begin(),--tmp,0) == accumulate(++tmp,nums.end(),0))
{
flag = 1;
break;
}
it++;
index++;
}
if(flag == 0)
{
index = -1;
}
return index;
}
};
//解法二:
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int i,index = -1;
int leftsum = 0,sum = 0;
for(i = 0;i < nums.size();i++)
{
sum += nums[i];
}
for(i = 0;i < nums.size();i++)
{
if(leftsum * 2 + nums[i] == sum)
{
index = i;
break;
}
leftsum += nums[i];
}
return index;
}
};
力扣刷题 19.寻找数组的中心下标——简单题
最新推荐文章于 2024-11-10 14:06:08 发布