給出定兩個參數,參數1:arr,參數2:num;查找參數num插入數組時的最小索引數組
getIndexToIns([10, 20, 30, 40, 50], 35) should return 3. getIndexToIns([10, 20, 30, 40, 50], 30) should return 2. getIndexToIns([2, 5, 10], 15) should return 3.
function getIndexToIns(arr,num) { var newArr = arr.sort((a,b) => a-b); for(var i=0; i<newArr.length; i++) { if(newArr[i] >= num) { return i; } } return newArr.length; } getIndexToIns([5, 3, 20, 3], 5);
1.用變量存儲num大於arr中各元素的次數
2.返回變量code
function getIndexToIns(arr,num) { var counts = 0; for(var i=0; i<arr.length; i++) { if(num > arr[i]) { counts++; } } return counts; } getIndexToIns([5, 3, 20, 3], 5);
function getIndexToIns(arr,num) { arr.sort((a,b) => a-b); var i = 0; while(num > arr[i]) { i++ } return i; } getIndexToIns([5, 3, 20, 3], 5);
1.數組重排序
2.查找大於num的數組最小值的索引
3.索引等於-1返回數組長度,不然返回索引排序
function getIndexToIns(arr,num) { var index = arr.sort((a,b) => a-b) .findIndex(a => a >= num); return index === -1 ? arr.length:index; } getIndexToIns([5, 3, 20, 3], 5);
function getIndexToIns(arr,num) { arr.push(num); arr.sort((a,b) => a-b); return arr.indexOf(num); } getIndexToIns([5, 3, 20, 3], 5);
function getIndexToIns(arr,num) { return arr.concat(num).sort((a,b) => a-b).indexOf(num); } getIndexToIns([5, 3, 20, 3], 5);
有其餘好的方法或思路的道友,不妨在沙發區神交一番。索引