leetcode34题——二分查找

leetcode34题——二分查找

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

思路

首先寻找左边界,即第一个出现目标值的位置。通过二分查找思想,一步一步缩小查找区间,最后判断是否越界即可。然后同理查找右边界即可。

代码:c语言
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
    int left = searchLeft(nums,numsSize,target);
    int right = searchRight(nums,numsSize,target);
    int* ret = malloc(sizeof(int) * 2);
    *returnSize = 2;
    ret[0] = left;
    ret[1] = right;
    return ret;
}
//查找左边界
int searchLeft(int* nums, int numsSize, int target){
    int left = 0;
    int right = numsSize - 1;
    int mid = 0;
    while(left <= right){
        mid = left + (right - left) / 2; //防溢出
        if(nums[mid] < target)//目标值更大
            left = mid + 1;
        else if (nums[mid] > target)//目标值更小
            right = mid - 1;
        else
            right = mid - 1;//与目标值一样,还得看前面是否还存在目标值
    }
    if(left >= numsSize || nums[left] != target)//目标值大于所有元素
        return -1;
    return left;
}
//查找右边界
int searchRight(int* nums, int numsSize, int target){
    int left = 0;
    int right = numsSize - 1;
    int mid = 0;
    while(left <= right){
        mid = left + (right - left) / 2; //防溢出
        if(nums[mid] < target)//目标值更大
            left = mid + 1;
        else if (nums[mid] > target)//目标值更小
            right = mid - 1;
        else
            left = mid + 1;//与目标值一样,还得看后面是否还存在目标值
    }
    if(right < 0 || nums[right] != target)//目标值小于所有元素
        return -1;
    return right;
}

你可能感兴趣的:(leetcode,leetcode,算法,排序算法,c语言)