LeetCode c语言-Search for a Range

本文介绍了一种在有序数组中查找特定目标值起始和结束位置的高效算法,要求时间复杂度为O(log n)。通过从两端逼近的方式,在避免了全数组扫描的同时确保了算法效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Title:

Given an array of integers sorted in ascending order, 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].



这道题给定一个排序好的数组,然后找到重复的数字,并输出序号即可。

该题的要求是时间复杂度为O(log n),也就是说不能采用从头遍历到尾的方法,容易超时。因此采用另一种做法,从两边同时向中间靠拢。由于是排序好的数组,因此判断逻辑较为简单。


Solution:

int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
    int *result=(int*)malloc(sizeof(int)*2);
    int i,j;
    int tmp;
    
 	if (numsSize<=0) {
 		*returnSize=2;
 		result[0]=-1;
 		result[1]=-1;
 		return result;
	}
    
    if (numsSize==1) {
        if (target==nums[0]) {
        *returnSize=2;
 		result[0]=0;
 		result[1]=0;
        return result;
        }
        else {
        *returnSize=2;
 		result[0]=-1;
 		result[1]=-1;
        return result;
        }
    }
	i=0;
	j=numsSize-1;

	while(i<j) {
		if (target<nums[i] || target>nums[j]){
			*returnSize=2;
			result[0]=-1;
 			result[1]=-1;
			return result;
		}
		else if (target==nums[i]) {
			tmp=i+1;
			while(tmp<numsSize && nums[tmp]==nums[i]) {
				tmp++;
			}
				*returnSize=2;
				result[0]=i;
				result[1]=tmp-1;
				return result;

		}

		else if (target==nums[j]) {
			tmp=j-1;
			while(tmp>=0 && nums[tmp]==nums[j]) {
				tmp--;
			}
		
				*returnSize=2;
				result[0]=tmp+1;
				result[1]=j;
				return result;
		}

		else {
            if (i+1==j-1)
			i++;
            else {
                i++;
                j--;
            }
			
		}
	}
    
    *returnSize=2;
	result[0]=-1;
    result[1]=-1;
    return result;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值