zoukankan      html  css  js  c++  java
  • LeetCode——Search for a Range

    1. Question

    Given an array of integers sorted in ascending order, 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].

    2. Solution

    二分查找,找最左边和目标相等的数,找右边和密保相等的数。 时间复杂度O(lgn)。

    3. Code

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            
            int start = 0;
            int end = nums.size() - 1;
            vector<int> res(2, -1);
            // 数组为空,注意判断
            if (nums.size() == 0)
                return res;
            // 找最左边和目标值相等
            while (start < end) {
                int mid = (start + end) >> 1;
                if (nums[mid] < target) start = mid + 1;
                else end = mid;
            }
            if (nums[start] == target)
                res[0] = start;
            else
                return res;
            
            end = nums.size() - 1;
            while (start < end) {
                int mid = ((start + end) >> 1) + 1;   // 使中间值偏向右边
                if (nums[mid] > target) end = mid - 1;
                else start = mid;
            }
            res[1] = end;
            return res;
        }
        
    };
    
  • 相关阅读:
    OCP-1Z0-053-V12.02-235题
    OCP-1Z0-053-V12.02-524题
    OCP-1Z0-053-V12.02-525题
    OCP-1Z0-053-V12.02-526题
    OCP-1Z0-053-V12.02-535题
    OCP-1Z0-053-V12.02-540题
    OCP-1Z0-053-V12.02-617题
    OCP-1Z0-053-V12.02-649题
    如何制作Jar包并在android中调用jar包
    JAVA实现回调
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7820090.html
Copyright © 2011-2022 走看看