day4-1107-leetcode查找1-Search for a Range

LeetCode-Search for a Range

题目

Given a sorted array of integers, 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].

分析

已经排好了序,用二分查找。

C++实现1

class Solution {
public:
	vector<int> searchRange(int A[], int n, int target) {
		const int l = distance(A, lower_bound(A, A + n, target));
		const int u = distance(A, prev(upper_bound(A, A + n, target)));
		if (A[l] != target) // not found
			return vector<int> { -1, -1 };
		else
			return vector<int> { l, u };
		}
};

C++实现2

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;


int lower_bound(vector<int>& arr, int key) {
    int half;
    int len = arr.size();
    int mid;
    int first = 0;
    while (len > 0) {
        half = len >> 1;
        mid = first + half;
        //in the right part
        if (arr[mid] < key) {
            first = mid + 1;
            //因为first=mid+1,所以这里的len需要在减去half的基础之上再减去1
            len = len - half - 1;
        } else {
            //in the left part
            len = half;
        }
    }
    return first;
}
int upper_bound(vector<int>& arr, int key) {
    int mid;
    int first = 0;
    int len = arr.size();
    int half;
    while (len > 0) {
        half = len >> 1;
        mid = half + first;
        if (arr[mid] > key) {//in the left part
            len = half;
        } else {//if arr[mid]<= key ,in the right part
            first = mid + 1;
            len = len - half - 1;
        }
    }
    return first;
}
	
class Solution {
public:
	vector<int> searchRange (vector<int>& arr,int target) {
		int lower = lower_bound(arr, target);
		int upper = upper_bound(arr, target);
		vector<int> res; 
		if (lower != -1)
			res.push_back(lower);
		res.push_back(upper-1);
		return res;
	}

};


int main(int argc, char** argv) {
	Solution sol;
	vector<int> arr1;
	arr1.push_back(5);
	arr1.push_back(7);
	arr1.push_back(7);
	arr1.push_back(8);
	arr1.push_back(8);
	arr1.push_back(10);
	
	int target = 8;
	vector<int> v =sol.searchRange(arr1,target);
	vector<int>::iterator it;
	for(it=v.begin(); it!=v.end();it++){	
		cout<<*it<<" "<<endl;	
	}
	system("pause"); 
	return 0;
}

备注

lower_bound算法要求在已经按照非递减顺序排序的数组中找到第一个大于等于给定值key的那个数,其基本实现原理是二分查找。
 upper_bound函数要求在按照非递减顺序排好序的数组中找到第一个大于给定值key的那个数,其基本实现原理是二分查找。
两种实现参考了stl中的实现方式,返回满足条件的值在数组中的下标。如果找不到满足条件的值,将会返回数组的大小,就像迭代器中的end一样,对应有效下标的下一个值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值