Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
給定一個陣列與目標值,如果在陣列中找到目標值,回傳索引值,如果沒有找到,回傳依照順序插入陣列的索引值。
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
這題使用暴力解法,
如果有找到直接回傳索引值,
如果沒有找到,將目標值放進陣列,排序後再取索引值。
var searchInsert = function(nums, target) {
if(nums.indexOf(target) !== -1){
return nums.indexOf(target)
}else{
nums.push(target);
nums.sort((a,b)=>a-b);
return nums.indexOf(target);
}
};