[LeetCode]Search for a Range

本文介绍了一种使用二分查找算法来解决寻找目标元素最左位置、最右位置及插入位置问题的方法。通过两个独立的函数findLeftMost和findRightMost实现了高效查找,适用于已排序的数组。
class Solution {
//Binary Search
//we must know how to process the 3 cases below:
//1.how to find the right most target
//2.how to find the left most target
//3.how to find the insert position
public:
	vector<int> searchRange(int A[], int n, int target) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int l = 0;
		int r = n-1;
		while (l <= r)
		{
			int mid = l+(r-l)/2;
			if (A[mid] >= target)//find the left most target 
				r = mid-1;
			else if (A[mid] < target)
				l = mid+1;
		}
		int left = l;
		l = 0; 
		r = n-1;
		while (l <= r)
		{
			int mid = l+(r-l)/2;
			if (A[mid] > target)//find the right most target
				r = mid-1;
			else if (A[mid] <= target)
				l = mid+1;
		}
		int right = r;
		if(A[left] != target || A[right] != target)
			left = right = -1;
		vector<int> ans(2);
		ans[0] = left;
		ans[1] = right;
		return ans;
	}
};

second time

class Solution {
public:
    int findLeftMost(int A[], int n, int target)
    {
        if(n == 0) return -1;
        int left = 0;
        int right = n-1;
        while(left < right)
        {
            int mid = left+(right-left)/2;
            if(A[mid] >= target) right = mid;
            else left = mid+1;
        }
        if(A[left] == target) return left;
        else return -1;
    }
    int findRightMost(int A[], int n, int target)
    {
        if(n == 0) return -1;
        int left = 0;
        int right = n-1;
        while(left <= right)
        {
            int mid = left+(right-left)/2;
            if(A[mid] > target) right = mid-1;
            else left = mid+1;
        }
        if(A[right] == target) return right;
        else return -1;
    }
    vector<int> searchRange(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int startPos = findLeftMost(A, n, target);
        int endPos = findRightMost(A, n, target);
        vector<int> ans(2);
        ans[0] = startPos; ans[1] = endPos;
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值