直接搜索会超时,只有30%,用二分法可以解决
#include <iostream>
#include <vector>
using namespace std;
int helper1(vector<int> vec, int num)
{
if( num <= 0 || num > vec[vec.size()-1])
{
return -1;
}
if(num < vec[0])
{
return 1;
}
int pre = 0, last = vec.size()-1;
while (pre < last)
{
int mid = pre + (last - pre) / 2;
if(vec[mid] < num)
{
pre = mid + 1;
}
else if(vec[mid] > num)
{
last = mid;
}
else
{
return mid + 1;
}
}
return pre + 1;
}
int main()
{
int n;
cin >> n;
vector<int> sum;
int temp;
int tep = 0;
for (int i = 0; i < n; i++)
{
cin >> temp;
tep += temp;
sum.push_back(tep);
}
int m;
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> temp;
cout << helper1(sum, temp) << endl;
}
return 0;
}