步长为一的数组中找数

来源:互联网 发布:mac book air跑分 编辑:程序博客网 时间:2024/05/18 09:33

有这样一个数组A,大小为n,相邻元素差的绝对值都是1。如:A={4,5,6,5,6,7,8,9,10,9}。现在,给定A和目标整数t,请找到t在A中的位置。除了依次遍历,还有更好的方法么?


#include <iostream>#include <stdio.h>#include <stdlib.h>#include <math.h>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;}


0 0