zoukankan      html  css  js  c++  java
  • Where do I belong (freeCodeCamp)

    先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。

    举例:where([1,2,3,4], 1.5) 应该返回 1。因为1.5插入到数组[1,2,3,4]后变成[1,1.5,2,3,4],而1.5对应的索引值就是1

    同理,where([20,3,5], 19) 应该返回 2。因为数组会先排序为 [3,5,20]19插入到数组[3,5,20]后变成[3,5,19,20],而19对应的索引值就是2

    //

    先对传入数组排序,然后通过遍历,找出插入点位置

    注意array.sort()方法的参数只可以是一个比较方法

    function where(arr, num) {
      // 请把你的代码写在这里
      var array=arr.sort(function(a,b){
        return a-b;//排序函数 function();
      });
     
      var postion=0;
      for(var i=0;i<arr.length;i++){
        if(num<=array[i]){
          postion=i;
          break;
        }
        else{
          array.push(num);//这里是插入的数字比数组元素大的情况,通过push()添加到数组中,然后postion获取数组末尾元素索引
          postion=array.length;
        }
        
      }
      return postion;
    }
    
    where([2, 5, 10], 19);
  • 相关阅读:
    纹理加载和异步
    地板上创建批量小方块
    创建自定义几何体(以立方体为例)
    WTForms
    angular和vue的差别
    vuejs简单介绍特点
    angularjs简单介绍和特点
    flask重要点
    redis
    DRF之认证组件源码解析
  • 原文地址:https://www.cnblogs.com/doudou2018/p/9610822.html
Copyright © 2011-2022 走看看