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

    解法:find函数,返回找到数字的迭代器,然后用distance函数返回下标值,后面就是循环找出相同的个数

    class Solution {
    public:
        vector<int> searchRange(vector<int>& nums, int target) {
            vector<int>::iterator it;
            vector<int> result;
            it = find(nums.begin(),nums.end(),target);
            if(it == nums.end()) {
                result.push_back(-1);
                result.push_back(-1);
                return result;
            }
            
            int i = distance(nums.begin(),it);
            int n = nums.size();
            result.push_back(i);
            while(*it == nums[++i] && i < n);  //确保++i不要数组溢出
            result.push_back(i-1);
            return result;
        }
    };
  • 相关阅读:
    数据结构上机思考
    hdu1005,循环节
    网络赛总结
    icpc沈阳网络赛。cake cake!
    树的基础代码
    网络赛第一场
    欧拉函数
    欧拉函数
    多校第十场
    (环上)最大子段和
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5319341.html
Copyright © 2011-2022 走看看