leetcode力扣 C/C++ 满分答案解析 34. 在排序数组中查找元素的第一个和最后一个位置

整理的合集链接放在这里了
leetcode力扣、PAT、CCF CSP历年真题C/C++满分答案 精心整理合集

其实是第一次做力扣的题,有点懵逼,不知道题目的输入输出格式是什么意思。
去看别人答案也是没有scanf和printf的,愣了一下才发现原来是让写接口,可能这样比较接近工作实际吧哈哈哈
leetcode力扣 C/C++ 满分答案解析 34. 在排序数组中查找元素的第一个和最后一个位置_第1张图片


#include 
#include 

int binarySearch(int* nums, int numsSize, int target)
{
    int id,l=0,r=numsSize-1;
    while(l<=r)
    {
        id = (l+r)/2;
        if(nums[id]==target)
            return id;
        else if(nums[id]>target)
            r = id-1;
        else
            l = id+1;
    }
    return -1;
}

int* searchRange(int* nums, int numsSize, int target, int* returnSize)
{
    int id = binarySearch(nums,numsSize,target);
    int* p = (int*)malloc(sizeof(int)*2);
    *returnSize = 2;
    if(id==-1)
    {
        p[0]=-1;
        p[1]=-1;
    }else
    {
        p[0]=id;
        p[1]=id;
        while(--p[0]>=0 && nums[p[0]]==target);
        p[0]++;
        while(++p[1]<numsSize && nums[p[1]]==target);
        p[1]--;
    }
    return p;
}


你可能感兴趣的:(Leetcode,CSP,PAT,题解合集,leetcode,c语言,c++)