• 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]
    };
  • 相关阅读:
    困扰多年的eclipse项目编码问题!
    什么是专注?什么是执行力?
    关于图表的理解
    去重与替换
    pandas 文本操作
    pandas 数值计算
    DatetimeIndex 时间序列
    Datatime 时间模块
    Numpy 常用方法
    Python迭代器 Iterator
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10409327.html
Copyright © 2020-2023  润新知