码迷,mamicode.com
首页 > 其他好文 > 详细

在相邻元素相差1的数组中查找某一特定元素第一次出现的位置

时间:2014-07-26 01:22:36      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   re   c   div   

题目:数组中相邻的每两个数之间的差值是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;
}

 

在相邻元素相差1的数组中查找某一特定元素第一次出现的位置,布布扣,bubuko.com

在相邻元素相差1的数组中查找某一特定元素第一次出现的位置

标签:style   blog   color   io   for   re   c   div   

原文地址:http://www.cnblogs.com/DayByDay/p/3868878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!