Search for a Range -- leetcode

来源:互联网 发布:终端服务的端口号 编辑:程序博客网 时间:2024/06/01 10:48

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].

https://oj.leetcode.com/problems/search-for-a-range/

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        int start = -1,end = -1,i;        bool flag = false;        for(i = 0 ;i < n; ++i)        {            if(A[i] == target && flag == false)            {                start = i;                flag = true;            }//找到了 则记录开始位置 并标记一下            else if(A[i] != target && flag)            {                end = i - 1;                break;            }//没找到 并且已经被标记过了 显然 end = i -1            else if(A[i] == target && flag)            {                end = i;            }//找到了 并且也标记过了 说明这是连续出现的情况             if(i == n-1 && flag && end == -1)            {                end = start;            }//找完了最后一个 并且标记了 并且end 还是初始值 注意这是单独的一个if 说明 最后一个才找到                     }        return vector<int> {start,end};    }};


很直接的思路 时间复杂度是 O(n)

如果用用二分查找 应该是O(logn) 

也可以拿现成的stl 算法 lowerbound 和upperbound


0 0
原创粉丝点击