LeetCode 算法题【Easy】:35. Search Insert Position

链接:https://leetcode.com/problems/search-insert-position/

Question

Given a sorted array of distinct integers 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 must write an algorithm with O(log n) runtime complexity.

Example 1:

1
2
Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

1
2
Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

1
2
Input: nums = [1,3,5,6], target = 7
Output: 4

My Answer

1
2
3
4
5
var searchInsert = function(nums, target) {
const index = nums.indexOf(target)
if (index > -1) return index
return [...nums, target].sort((a, b) => a - b).indexOf(target)
};

My Answer’s Performance

1