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]
// ConsoleApplication8.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;

/*//这个算法中,first是最终要返回的位置
int lower_bound(int *array, int size, int key)
{
    int first = 0, len = size;
    int mid, half;
    while (len > 0) {
        half = len >> 1;
        mid = first + half;
        if (array[mid] > key) {
            len = half;
        }
        else {
            first = mid + 1;
            len = len - half - 1;
        }
    }
    return first;
}
int main()
{
    int a[] = { 1, 2, 4, 4, 5, 6, 7, 8, 9, 10 };
    int n;
    cin >> n;
    int answer = lower_bound(a, 10, n);
    cout << answer << endl;
    return 0;
}*/

int main()
{
    int a[] = { 5,7,7,8,8,10 };
    int n;
    cin >> n;
    pair<int, int>answer;
    int first = 0, len = sizeof(a) / sizeof(a[0]);
    int mid, half;
    while (len > 0) {
        half = len >> 1;
        mid = first + half;
        if (a[mid] < n) {
            first = mid + 1;
            len = len - half - 1;
        }
        else
            len = half;
    }
    answer.first = first;
    first = 0, len = sizeof(a) / sizeof(a[0]);
    while (len > 0) {
        half = len >> 1;
        mid = first + half;
        if (a[mid] > n) {
            len = half;
        }
        else {
            first = mid + 1;
            len = len - half - 1;
        }
    }
    answer.second = first;
    if (answer.first == answer.second) {
        /*如果大于等于和大于的位置一样,那么这个数不存在*/
        answer.first = -1, answer.second = -1;
        cout << "sorry" << endl;
        cout << answer.first << " " << answer.second << endl;
    }else
        cout << answer.first << " " << answer.second-1 << endl;

}

猜你喜欢

转载自blog.csdn.net/qq_30366449/article/details/78568090