1. 程式人生 > >Where do I belong(算法)

Where do I belong(算法)

asc 思路 lan art per spa pan objects pretty

題目

我身在何處?

先給數組排序,然後找到指定的值在數組的位置,最後返回位置對應的索引。

舉例: 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 .

Where do I belong(算法)