《leetCode》:Search for a Range

题目

Given a sorted array of integers, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

思路

思路为:用二分查找分别查找目标数在数组中的起点的终点。


#include<stdio.h>
#include<stdlib.h>

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int binarySearch(int *nums,int begin,int end,int target,bool flag){
    if(nums==NULL||begin>end){
        return -1;
    } 
    int mid=begin+end>>1;
    int val=nums[mid];
    if(val==target){
        //根据传送过来的flag来判断是否是寻找的是起点还是终点的下标。 
        int index=flag?(binarySearch(nums,begin,mid-1,target,flag)) :(binarySearch(nums,mid+1,end,target,flag));
        return index==-1?mid:index;
    }
    else if(val>target){
        end=mid-1;
        return binarySearch(nums,begin,end,target,flag);
    }
    else{
        begin=mid+1;
        return  binarySearch(nums,begin,end,target,flag);
    }

    return -1;//没找到返回 -1 

} 
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
    //先构造没有找到时要返回的数组result 
    *returnSize=2;
    int *result=(int *)malloc(2*sizeof(int));

    if(result==NULL){
        exit(EXIT_FAILURE);
    }
    result[0]=-1;
    result[1]=-1; 
    if(nums==NULL||numsSize<1){
        return result;
    }
    int begin=0;
    int end=numsSize-1;
    //应用两次二分查找来寻找目标数的起点和终点。 
    int startIndex=binarySearch(nums,begin,end,target,true);
    int endIndex=binarySearch(nums,begin,end,target,false);

    if(startIndex==-1&&endIndex==-1){//没有找到 

        return result;
    }
    //*returnSize=(endIndex-startIndex)+1;
    result[0]=startIndex;
    result[1]=endIndex;     
    return result;
}

//测试函数
int main(void){
    int k;
    int target;
    while(scanf("%d  %d",&k,&target)!=EOF&&k>0){
        int *arr=(int *)malloc(k*sizeof(int));
        if(arr==NULL){
            exit(EXIT_FAILURE);
        }
        for(int i=0;i<k;i++){//输入一个排序的数组 
            scanf("%d",arr+i);
        }
        int returnSize=0;
        int *result=searchRange(arr, k, target, &returnSize);
        for(int i=0;i<returnSize;i++){
            printf("%d   ",result[i]);
        }
        printf("\n");
    }
    return 0;
}

在完成此题的过程中遇到了如下问题:

出现这个的原因是:我把returnSize这个变量给理解错了。
实在是想不通要这个returnSize这个变量干什么,还误导了我,我原以为是用returnSize这个变量来表示,数组中有多少个目标数,调试了一会,才发现问题再这里。

AC结果如下:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值