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

    解题思路:

    二分查找

     1 class Solution {
     2 public:
     3     vector<int> searchRange(vector<int>& nums, int target) {
     4         vector<int> result;
     5         int len = nums.size();
     6         int first = 0;
     7         int last = len - 1;
     8         while (first <= last) {
     9             int mid = first + (last - first) / 2;
    10             if (nums[mid] == target) {
    11                 int l1 = mid;
    12                 int l2 = mid;
    13                 while (--l1 >= 0 && nums[l1] == target);
    14                 while (++l2 < len && nums[l2] == target);
    15                 result.push_back(++l1);
    16                 result.push_back(--l2);
    17                 break;
    18             } else if (target < nums[mid]) {
    19                 last = mid - 1;
    20             } else {
    21                 first = mid + 1;
    22             }
    23         }
    24         
    25         if (result.size() == 0) {
    26             result.push_back(-1);
    27             result.push_back(-1);
    28         }
    29         
    30         return result;
    31     }
    32 };
  • 相关阅读:
    Javascript事件模型
    关于node.js(一)
    JavaScript表单编程总结
    使用Dom操纵样式表
    文档对象模型Dom
    浏览器对象模型BOM总结
    在javascript中正则表达式的概念与应用
    CSS块级元素、内联元素概念
    HTTP协议
    [学习记录]BFS思路详解
  • 原文地址:https://www.cnblogs.com/skycore/p/4941164.html
Copyright © 2020-2023  润新知