Search for a Range 两种解法

来源:互联网 发布:sqlyog执行sql文件 编辑:程序博客网 时间:2024/06/11 21:42

自己的版本,二分查找,找到的时候利用while循环,找附近相等的元素,找到最小和最大的加入vector

注意二分的条件  pre <= post 否则容易出现死循环,其次题目的意思是要找最大和最小两个index,而不是所有的,开始把题意理解错了

class Solution {public:    vector<int> searchRange(int A[], int n, int target) {        vector<int> re;        if(n == 0)            return re;        int mid,pre = 0,post = n-1;        while(pre <= post ){   //注意这里的条件是pre <= post而不是 pre != post,因为pre可能出界            mid = (pre + post)/2 ;            if(A[mid] == target){                int tmp = mid;                while(A[mid] == A[mid-1]&& mid-1 >= 0)                    mid-- ;                re.push_back(mid);                while(A[tmp] == A[tmp+1] && tmp+1 < n){                     tmp++;                }                re.push_back(tmp);                return re;            }            else if(A[mid] < target)                    pre = mid+1;            else                post = mid-1;            mid = (pre + post)/2;        }        re.push_back(-1);        re.push_back(-1);        return re;    }};

另外看到一种利用distance函数的解法
http://www.cplusplus.com/reference/iterator/distance/

Calculates the number of elements between first and last.用来计算first到last的元素个数

// 时间复杂度 O(logn) ,空间复杂度 O(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 };    }};

两种算法时间都是56ms

STL中关于二分查找的函数有三个lower_bound 、upper_bound 、binary_search 。这三个函数都运用于有序区间(当然这也是运用二分查找的前提),下面记录一下这两个

函数。

C++ STL中提供了std::next_permutation与std::prev_permutation可以获取数字或者是字符的全排列,其中std::next_permutation提供升序、std::prev_permutation提供降序。

 

lower_bound(k)返回一个迭代器,指向键不小于k的第一个元素

upper_bound(k)返回一个迭代器,指向键大于k的第一个元素

\




0 0