题解 | #找出指定数在数组中的范围#

找出指定数在数组中的范围

http://www.nowcoder.com/practice/3783c394c5d84d5ab9e55d91a6efeb8c

二分法查找
#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n,tar;
    while(scanf("%d",&n)!=EOF){
        scanf("%d",&tar);
        int ch[n],i;
        for(int i=0;i<n;i++){
            scanf("%d",&ch[i]);
        }
        int left=0,right=n-1,temp;
        if(ch[left]==tar){
            i=left;
            while(ch[i]==tar&&i<n){
                i++;
            }
            printf("[%d,%d]\n",left,i-1);
        }
        else if(ch[right]==tar){
            i=right;
            while(ch[i]==tar&&i>=0){
                i--;
            }
            printf("[%d,%d]\n",i+1,right);
        }
        else if(n<=2){
            printf("[-1,-1]\n");
        }
        /*begin:二分法查找target*/
        else{
            int flag=0;
            while(right>left){
                temp=(left+right)/2;
                if(ch[temp]>tar){
                    right=temp;
                }
                else if(ch[temp]<tar){
                    left=temp;
                }
                else if(ch[temp]==tar){
                    flag=1;
                    break;
                }
                if(right-left==1){
                    break;
                }
            }
            /*end:二分法查找target*/
            if(flag==0){
                printf("[-1,-1]\n");
            }
            else{
                int l,r;
                for(i=temp;i<right;i++){
                    if(ch[i]==tar){
                        r=i;
                    }
                    else{
                        break;
                    }
                }
                for(i=temp;i>left;i--){
                    if(ch[i]==tar){
                        l=i;
                    }
                    else{
                        break;
                    }
                }
                printf("[%d,%d]\n",l,r);
            }
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 18:54
说等下个版本吧的发呆爱好者很贪睡:佬最后去了哪家呀
点赞 评论 收藏
分享
把球:这个听过,你加了就会发现是字节的hr
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务