llllmz

导航

34. 在排序数组中查找元素的第一个和最后一个位置C

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
    *returnSize=2;
    int* a=(int*)malloc(sizeof(int)*2);
    a[0]=-1;
    a[1]=-1;
    int head=0,tail=numsSize-1;
    while(head<=tail){
        int mid=(head+tail)/2;
        if(nums[mid]<target){
            head=mid+1;
        }else if(nums[mid]>target){
            tail=mid-1;
        }else{
            head=mid;
            tail=mid;
            while(head> 0 && nums[head-1]==target ) head--;
            while(tail<numsSize-1 && nums[tail+1]==target ) tail++;
            a[0]=head;
            a[1]=tail;
            break;
        }
    }
    return a;
}

posted on 2024-02-26 19:08  神奇的萝卜丝  阅读(7)  评论(0)    收藏  举报