# 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. 若给定target小于数组第一个元素，返回0；
2. 若target大于最后一个元素，返回n

 1 class Solution {
2 public:
3     int searchInsert(int A[], int n, int target) {
4         if(A == NULL || n < 1)
5             return -1;
6         if(target < A[0])
7             return 0;
8         if(target > A[n-1])
9             return n;
10
11         int low = 0;
12         int high = n-1;
13
14         int mid = 0;
15
16         while(high-low>1){
17             mid = low + (high - low)/2;
18             if(A[mid] == target)
19                 return mid;
20             else if(A[mid] > target)
21                 high = mid;
22             else
23                 low = mid;
24         }
25
26         if(high-low ==1)
27             if(A[low] == target)
28                 return low;
29             if(A[high] == target)
30                 return high;
31             else
32                 return low+1;
33
34     }
35 };

posted @ 2014-10-29 11:35  非著名程序师  阅读(426)  评论(0编辑  收藏