在相邻元素相差1的数组中查找某一特定元素第一次出现的位置
题目:数组中相邻的每两个数之间的差值是1或-1,给定一个数N,求如何找到第一个N的位置。
如:3,4,3,2,1,2,3,4,3,4,5,6,5 求第一个5所在的位置。
#include <stdio.h> #include <stdlib.h> int main(void) { int a[] = {3,4,3,2,1,2,3,4,3,4,5,6,5}; int i, next, to_search; int len = sizeof(a); int count = 0, found = 0; printf("Please input the number that you want to search: "); scanf("%d",&to_search); for( i=0; i<len; i+=next) { ++count; if( a[i] == to_search ) { found = 1; break; } else next = abs(a[i]-to_search); } printf("Search times: %d\n",count); if( found ) printf("%d is at a[%d]\n",to_search, i); else printf("Not found.\n"); return 0; }