首页 > 其他 > 详细

Search Insert Position

时间:2014-11-22 13:14:29      阅读:111      评论:0      收藏:0      [点我收藏+]

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 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         if(A.length == 0)
 4             return 0;
 5         int low = 0;
 6         int high = A.length - 1;
 7         int middle = 0;
 8         
 9         while(low <= high){
10             middle = (low + high) / 2;
11             if(target > A[middle]){
12                 low = middle + 1;
13                 
14             }
15             else if(target < A[middle]){
16                 high = middle - 1;
17             
18             }
19             else
20                 return middle;
21         }
22         if(A[middle] < target)
23             return middle + 1;
24         if(middle == 0){
25             return middle;
26         }
27         return middle;
28     }
29 }

 

Search Insert Position

原文:http://www.cnblogs.com/luckygxf/p/4114993.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!