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;
        }
    };
  • 相关阅读:
    js 和 jquery的宽高
    client、offset、scroll
    web开发中会话跟踪的方法有哪些
    前端需要注意哪些SEO
    ES6 Set和Map数据结构
    ES6实现数组去重
    ES6 Symbol
    ES6对象的拓展
    ES6数组的拓展
    ES6函数的拓展
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5319341.html
Copyright © 2011-2022 走看看