设为首页 加入收藏

TOP

LeetCode-Search for a Range
2015-07-20 17:24:48 来源: 作者: 【 】 浏览:2
Tags:LeetCode-Search for 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].

解题分析:就是一个二分搜索的应用,不难。但是就是注意一个数组越界的检查。LeetCode自己的编译器会报错。

?

int a,b;
?a=num;
?b=num;
while(A[a] == target )  a--;
while(A[b] == target )  b++;
最开始的时候,代码是这样的,对二分搜索找到了target,再进行往前往后的找。在codeblocks上运行是无错, 但就是提交在LeetCode上面会出现问题。

?

最后做了一个数组的溢出判断,终于AC了

?

int a,b;
        a=num;
        b=num;
        while(A[a] == target && a >= 0)  a--;
        while(A[b] == target && b <= n-1)  b++;

?

?

?

?

class Solution {
private: int binary_search(int* a, int len, int goal)
    {
    int low = 0;
    int high = len - 1;
    while(low <= high)
    {
        int middle = (low + high)/2;
        if(a[middle] == goal)
            return middle;
        else if(a[middle] > goal)
            high = middle - 1;
        else
            low = middle + 1;
    }
    return -1;
    }

public:
    vector
  
    searchRange(int A[], int n, int target) {
        vector
   
     s; int num = binary_search(A,n,target); if(num == -1) {s.push_back(-1);s.push_back(-1);} else { int a,b; a=num; b=num; while(A[a] == target && a >= 0) a--; while(A[b] == target && b <= n-1) b++; s.push_back((++a)); s.push_back((--b)); } return s; } };
   
  


?

?




?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇输入两个正整数,求其最大公约数 下一篇hdu4135--Co-prime(欧拉函数+容..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Linux_百度百科 (2025-12-26 12:51:52)
·Shell 流程控制 | 菜 (2025-12-26 12:51:49)
·TCP/UDP协议_百度百科 (2025-12-26 12:20:11)
·什么是TCP和UDP协议 (2025-12-26 12:20:09)
·TCP和UDP详解 (非常 (2025-12-26 12:20:06)