• LeetCode 34. Search for a Range


    Description

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

    my program

    (1)时间复杂度为O(n)

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            int i = 0, j = nums.size() -1;
            vector<int> res;
            while (i < nums.size())
            {
                if (nums[i] == target)  
                    break;
                i++;
            }
            while ( j>= 0)
            {
                if (nums[j] == target)  
                    break;
                j--;
            }
            if (i>=nums.size())
            {
                res.push_back(-1);
                res.push_back(-1);
            }else
            {
                res.push_back(i);
                res.push_back(j);
            }
            return res;
        }
    };

    (2)时间复杂度为O(logn),利用二分查找

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
        int begin = 0, end = nums.size(), mid, left, right;
        while (begin < end) {
            mid = (begin + end) / 2;
            if (nums[mid] >= target)
                end = mid;
            else
                begin = mid + 1;
        }
        left = begin;
        begin = 0, end = nums.size();
        while (begin < end) {
            mid = (begin + end) / 2;
            if (nums[mid] > target)
                end = mid;
            else
                begin = mid + 1;
        }
        right = begin;
        return left == right ? vector<int> {-1,-1} : vector<int> {left,right-1};
        }
    };

    先找左边界。当mid >= target,将end移动到mid,否则(mid < target),begin = mid+1;

    再找右边界。 当mid > target,将end移动到mid,否则(mid <= target),begin = mid+1;最后begin和end可能在target的左面一个。

    如果没有数组中target的话,那么left和right会指到同一个值上,否则的话就意味着出现了target,此时left指向第一个出现的target,而right是指向最后一个target的下一个值,所以right需要减去1.

  • 相关阅读:
    java中 == 与equals 的区别
    java中的多线程 // 基础
    MySQL-锁机制
    将博客搬至CSDN
    MySQL-事务
    MySQL-存储过程
    MySQL-触发器
    MySQL-视图
    Redis设置Auth认证保护
    PHP目前常见的五大运行模式
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391352.html
Copyright © 2020-2023  润新知