35. Search Insert Position
Leetcode
https://leetcode.com/problems/search-insert-position/
題目
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:
Input: nums = [1,3,5,6], target = 5
Output: 2Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4Example 4:
Input: nums = [1,3,5,6], target = 0
Output: 0Example 5:
Input: nums = [1], target = 0
Output: 0解答
方法一
var searchInsert = function(nums, target) {
const n = nums.length-1;
let low = 0;
let high = n;
if(target <= nums[low]) return 0;
if(target === nums[high]) return n;
// 如果大於最大的元素,插入到最後一個 index
if(target > nums[high]) return n+1;
while(low < high) {
const mid = Math.floor((low + high) / 2);
if(nums[mid] === target) return mid;
if(nums[mid] > target) {
high = mid;
} else {
low = mid + 1;
}
}
return low;
};Runtime: 72 ms, faster than 78.31% of JavaScript online submissions for Search Insert Position.
Memory Usage: 40 MB, less than 28.88% of JavaScript online submissions for Search Insert Position.
Last updated
Was this helpful?