35. Search Insert Position
Posted 暗影侠客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了35. Search Insert Position相关的知识,希望对你有一定的参考价值。
35. Search Insert Position
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.
Here are few examples.[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number} 5 */ 6 var searchInsert = function(nums, target) { 7 8 var len = nums.length; 9 var i,j,start,end; 10 start = end = 0; 11 j = len -1; 12 i = 0; 13 14 while (i<=j){ 15 16 var mid = Math.floor((i+j)/2); 17 18 if(target === nums[mid]){ 19 20 return mid; 21 22 } 23 24 25 if(target > nums[mid]){ 26 i = mid +1; 27 }else{ 28 j = mid -1; 29 } 30 31 } 32 33 return j + 1; 34 };
以上是关于35. Search Insert Position的主要内容,如果未能解决你的问题,请参考以下文章
#LeetCode# 35. Search Insert Position
LeetCode 35. Search Insert Position