35. Search Insert Position

时间:2017-10-22 19:17:16   收藏:0   阅读:246

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 };

 

原文:http://www.cnblogs.com/huenchao/p/7710534.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!