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

1.给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]。

进阶:

你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
 

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:

输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:

输入:nums = [], target = 0
输出:[-1,-1]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

类似的题目

剑指 Offer 53 - I. 在排序数组中查找

统计一个数字在排序数组中出现的次数。

示例 1:

输入: nums = [5,7,7,8,8,10], target = 8
输出: 2
示例 2:

输入: nums = [5,7,7,8,8,10], target = 6
输出: 0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:


int binary_find(int *nums, int numsSize, int target) {
    int low = 0;
    int high = numsSize - 1;
    int mid = 0;
    int midVal = 0;
    
    while (low <= high) {
        mid = (low + high) / 2;
        midVal = nums[mid];

        if (midVal < target) {
            low = mid + 1;
        } else if (midVal > target) {
            high = mid - 1;
        } else {
            return mid;
        }
    }

    return -1;
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
在排序数组中查找元素的第一个和最后一个位置
 */
int* searchRange(int* nums, int numsSize, int target, int* returnSize){
    int find = binary_find(nums, numsSize, target);
    int i = 0;

    int *array = (int *)calloc(2, sizeof(int));
    *returnSize = 2;

    if (-1 == find) {
        array[0] = -1;
        array[1] = -1;
    } else {
        array[0] = find;
        array[1] = find;
        i = find + 1;
        while (i < numsSize) {
            if (nums[i] == target)
            {
                array[1] = i;
            } else {
                break;
            }
            i++;
        }

        i = find -1;
        while (i >= 0) {
            if (nums[i] == target) {
                array[0] = i;
            } else {
                break;
            }
            i--;
        }
    }

    return array;
}

/* 数字在排序数组中出现的次数 */
int search(int* nums, int numsSize, int target){
    int find = binary_find(nums, numsSize, target);
    int i = 0;
    int count = 0;
    if(-1 == find) {
        return 0;
    }

    count++;
    i = find + 1;
    while(i < numsSize) {
        if(nums[i] == target) {
            count++;
        } else {
            break;
        }
        i++;
    }

    i = find - 1;
    while(i >= 0) {
        if(nums[i] == target) {
            count++;
        } else {
            break;
        }
        i--;
    }

    return count;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值