题解 | #求目标值的区间#

求目标值的区间

https://www.nowcoder.com/practice/e302d06bcdac4171b9768fd354922880


class Solution {
  public:
    /**
     *
     * @param A int整型一维数组
     * @param n int A数组长度
     * @param target int整型
     * @return int整型vector
     */
    vector<int> searchRange(int* A, int n, int target) {
        int l = 0, h = n, m;
        int start = -1, end = -1;
        while (l < h) {
            m = (l + h) / 2;
            if (A[m] > target) {
                h = m;
            } else if (A[m] < target) {
                l = m + 1;
            } else {
                int index = m;
                while (index >= 0 && A[index] == target)index--;
                start = index + 1;
                index = m;
                while (index < n && A[index] == target)index++;
                end = index - 1;
                break;
            }
        }
        vector<int> res;
        res.push_back(start);
        res.push_back(end);
        return res;
    }
};

全部评论

相关推荐

xxxxOxo:这公司幽默得很,要了简历半天一点动静都没有,过一会就给你发个邮件让你做测试,做完又没后文了,纯溜人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务