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

题目

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值