码迷,mamicode.com
首页 > 其他好文 > 详细

35. Search Insert Position

时间:2017-10-22 21:49:12      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:pos   code   style   dup   while   insert   value   start   nbsp   

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

标签:pos   code   style   dup   while   insert   value   start   nbsp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!