# 链家网-后台开发工程师笔试题-第三题

### 题目描述

#### 输入描述

5
2 7 3 4 9
3
1 25 11


### 题目输出

1
5
3


### 数据范围

1<= N <= 10^5, 1<= 每个组的成员数量 <= 10^6, 1<= M <= 10^5.

## 解题代码

#### 方法一： 直接做

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <stdexcept>
using namespace std;

const int maxn = 100000 + 5;
long long arr[maxn];
long long brr[maxn];

int main()
{
int n;
cin >> n;
arr[0] = 0;
for(int i = 1; i <= n; i++)
cin >> arr[i];
for(int i = 2; i <= n; i++)
arr[i] = arr[i] + arr[i-1];

int m;
cin >> m;
for(int i = 1; i <= m; i++)
cin >> brr[i];
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++)
{
if(arr[j] >= brr[i])
{
cout << j << endl;
break;
}
}
}

return 0;
}


#### 方法二： 用二分查找代替顺序查找

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;

const int maxn = 100000 + 5;
long long arr[maxn];
long long brr[maxn];

int bSearch(long long arr[], int left, int right, long long val)
{
while(left < right)
{
int mid = left + (right - left)/2;
if(arr[mid] < val)
left = mid+1;
else if(arr[mid] > val)
right = mid;
else
return mid;
}

return left;
}

int main()
{
int n;
cin >> n;
arr[0] = 0;
for(int i = 1; i <= n; i++)
cin >> arr[i];
for(int i = 2; i <= n; i++)
arr[i] = arr[i] + arr[i-1];

int m;
cin >> m;
for(int i = 1; i <= m; i++)
cin >> brr[i];
for(int i = 1; i <= m; i++)
{
cout << bSearch(arr, 1, n+1, brr[i]) << endl;
}

return 0;
}


#### 方法三： 空间换时间， 排序+hash

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;

const int maxn = 100000 + 5;
long long arr[maxn];
long long brr[maxn];
long long crr[maxn];

int main()
{
int n;
cin >> n;
arr[0] = 0;
for(int i = 1; i <= n; i++)
cin >> arr[i];
for(int i = 2; i <= n; i++)
arr[i] = arr[i] + arr[i-1];

int m;
cin >> m;
for(int i = 1; i <= m; i++)
{
cin >> brr[i];
crr[i] = brr[i];
}

unordered_map<long long, long long> mm;
sort(crr+1, crr+m+1);
int pos = 1;
int i = 1;
while(i <= n)
{
if(pos > m)
break;

while(arr[i] < crr[pos])
i++;
mm[crr[pos]] = i;
pos++;
}

for(int i = 1; i <= m; i++)
cout << mm[brr[i]] << endl;

return 0;
}



posted @ 2017-08-19 21:46  草滩小恪  阅读(204)  评论(0编辑  收藏