[C语言][LeetCode][34]Search for a Range

来源:互联网 发布:想在淘宝直播 编辑:程序博客网 时间:2024/04/30 02:19

题目

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].

标签

Array、Binary Search

难度

适中

分析

题目意思是给定一个排好序的整型数组和一个整型,然后找到这个整型在这个数组的起始位置和结束位置,并返回对应的下标,如果没有找到,返回[-1,-1]。这里的做法是,从数组开头查找起始位置,从数组末尾查找结束位置。

C代码实现

/** * 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 i=0;    int start=0, end=0;    bool startFlag = false;    bool endFlag = false;    int * array = (int *)malloc(sizeof(int)*2);    for(i=0; i<numsSize; i++)    {        if(target == nums[i])        {            start = i;            startFlag = true;            break;        }    }    for(i=numsSize-1; i>=0; i--)    {        if(target == nums[i])        {            end = i;            endFlag = true;            break;        }    }    *returnSize = 2;    if((true ==startFlag) && (true ==endFlag))    {        array[0] = start;        array[1] = end;        }    else    {        array[0] = -1;        array[1] = -1;     }    return array;}
0 0
原创粉丝点击