leetcode(34) - Search for a Range

来源:互联网 发布:辐射4enb画质优化补丁 编辑:程序博客网 时间:2024/05/06 13:10

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,

nums:   [5, 7, 7, 8, 8, 8, 8, 8, 10] 
target:   8

return

[3,7]



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







0 0
原创粉丝点击