一个百度的面试题及参考答案

2014-11-23 21:40:10 · 作者: · 浏览: 22

题目:


A的大小为n,其中的每相邻的两个元素之间差的绝对值为1,例如A={4 5 6 5 6 7 8 9 10 9},给定A和t,设计一个程序,求出t在A中的位置。


参考答案:


#include
#include
#include
#include
using namespace std;


int fun(int a[], int n, int k)
{
int pos = 0;
while (pos < n)
{
//从a[pos]到k至少要走abs(k-a[pos])步
pos += abs(k – a[pos]);
if (a[pos] == k)
{
return pos;
}
}


return -1;
}