Where do I belong

本文介绍了一个简单的JavaScript函数,用于对数组进行排序,并找到特定数值在排序后数组中的位置。通过示例展示了如何实现这一功能。

数组排序并找出元素索引

我身在何处?

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

举例:where([1,2,3,4], 1.5)

function where(arr, num) {
  // 请把你的代码写在这里
  arr.push(num);
  arr.sort(function(a,b){
    return a-b;
  });
  for(var i =0;i<arr.length;i++){
    if(arr[i]>=num){
      return i;
    }
  }
  return arr.length;
}

where([40, 60], 50);

 

该返回 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

当你完成不了挑战的时候,记得开大招'Read-Search-Ask'。

转载于:https://www.cnblogs.com/meng2017/p/7500519.html

There are 2n vertices (n is even ), n of which belong to set A , and the rest n belong to set B . Initially, there are m undirected edges in the graph, where the two vertices of each edge are not in the same set. In addition, there is no common vertex between any two edges. You are required to do the following operation multiple times: - Choose a vertex from set A and another from set B on the condition that these two vertices are not directly connected by an edge. Then add an edge to connect the two vertices. After that, when you choose any vertex in set A and any vertex in set B , the following conditions must be satisfied: - The two vertices are connected, which means there exists a path that leads from one vertex to the other. - The number of edges in the longest simple path between the two vertices is strictly greater than n . (In a simple path, each vertex is visited no more than once.) Please minimize the number of edges you add. Input The first line contains a single integer T (1≤T≤103) , representing the number of test cases. For each test case, the first line of the input contains two integers n and m (2≤n≤103,0≤m≤n , n is even ), representing the number of vertices in one set and the number of initial edges. In the following m lines, each line contains two integers u and v (1≤u,v≤n ), indicating an edge between the u -th vertex in set A and the v -th vertex in set B . It's guaranteed that there is no common vertex between any two edges. Output For each test case, if there is no solution, print -1 in a single line. Otherwise, the first line of the output contains an integer k , indicating the minimum number of edges you add. In the following k lines, the i -th line contains two integers ci and di (1≤ci,di≤n ), indicating an edge you add between the ci -th vertex in set A and the di -th vertex in set B . As there may be multiple valid solutions, you need to output the answer which makes the sequence c1,d1,c2,d2,…,ck,dk have
09-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值