zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Intent
    What should we do next in general after collecting relevant data
    NOTE FOR Secure Friend Discovery in Mobile Social Networks
    missing pcap.h
    after building Android Source code
    plot point(one column)
    When talking to someone else, don't infer that is has been talked with others at first. It may bring repulsion to the person who is talking with you.
    进程基本知识
    Python input和raw_input的区别
    强制 code review:reviewboard+svn 的方案
  • 原文地址:https://www.cnblogs.com/yangjiannr/p/7391352.html
Copyright © 2011-2022 走看看