zoukankan      html  css  js  c++  java
  • [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 };
  • 相关阅读:
    Markdown
    异异还原
    程序和算法
    运算符
    Java复习1
    复习总结
    为什么Byte是8位,但是却只能表示到127,而不是255?
    笔记的认识
    笔记本触摸板
    电脑热键
  • 原文地址:https://www.cnblogs.com/skycore/p/4941164.html
Copyright © 2011-2022 走看看