zoukankan      html  css  js  c++  java
  • 34. Find First and Last Position of Element in Sorted Array(js)

    34. Find First and Last Position of Element in Sorted Array

    Given an array of integers nums 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].

    Example 1:

    Input: nums = [5,7,7,8,8,10], target = 8
    Output: [3,4]

    Example 2:

    Input: nums = [5,7,7,8,8,10], target = 6
    Output: [-1,-1]
    题意:给定一个排好序的数字数组,返回匹配到target的第一项和第二项的索引
    代码如下:
    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var searchRange = function(nums, target) {
        
        var res=[];
        var count=0;
        for(var i=0;i<nums.length;i++){
            if(nums[i]===target){ res.push(i);count++; break;}
        }
        for(var i=nums.length-1;i>=0;i--){
            if(nums[i]===target) {res.push(i);count++; break;}
        }
        if(count==2) return res;
        return [-1,-1]
    };
  • 相关阅读:
    html5——渐变
    html5——背景
    html5——边框
    html5——私有前缀
    html5——盒子模式
    html5——文本阴影
    html5——颜色
    html5——css选择器
    html5——DOM扩展
    html5——多媒体(一)
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10409327.html
Copyright © 2011-2022 走看看