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

    题目

    我身在何处?

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

    举例:  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()

    思路

    先把指定的值加入数组,然后升序排序数组,最后用  indexOf() 方法返回传入值在数组中的位置。 

    解法

    function where(arr, num) {
      // Find my place in this sorted array.
      arr.push(num);
      arr.sort(function(v1,v2){
        return v1 - v2;
      });
      return arr.indexOf(num);
    }

    测试

    where([10, 20, 30, 40, 50], 35) 应该返回  3 . 

    where([10, 20, 30, 40, 50], 30) 应该返回  2 . 

    where([40, 60], 50) 应该返回  1 . 

    where([3, 10, 5], 3) 应该返回  0 . 

    where([5, 3, 20, 3], 5) 应该返回  2 . 

    where([2, 20, 10], 19) 应该返回  2 . 

    where([2, 5, 10], 15) 应该返回  3 . 

     
  • 相关阅读:
    window 7/8/10 安装nginx
    全面了解 Nginx 到底能做什么
    MySQL优化
    office 2013 破解工具 及 软件下载
    centos6+如何对外开放80,3306端口号或者其他端口号
    CentOS 中查看软件的版本号
    CentOS 中安装 mysql 5.7+
    STL入门大全(待编辑)
    Feign
    微信公众号
  • 原文地址:https://www.cnblogs.com/codepen2010/p/6825074.html
Copyright © 2011-2022 走看看