Search Insert Position [LeetCode]

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

Summary: basic binary search stuff.

 1     int searchInsert(int A[], int n, int target) {
 2         int start = 0;
 3         int end = n - 1;
 4         while(start <= end) {
 5             int median = start + (end - start + 1) / 2;
 6             if(target == A[median]) {
 7                 return median;
 8             }else if(target < A[median]) {
 9                 if(median - 1 >= 0 && target > A[median - 1])
10                     return median;
11                 if(median == 0)
12                     return 0;
13                 end = median - 1;
14             }else {
15                 if(median + 1 <= n - 1 && target < A[median + 1])
16                     return median + 1;
17                 if(median == n - 1)
18                     return n;
19                 start = median + 1;
20             }
21         }
22     }

 

posted @ 2013-11-15 14:17  假日笛声  阅读(169)  评论(0编辑  收藏  举报