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

思路:二分查找,注意最终终止时st和en的位置,st在后,en在前,所以应该返回st。

深入思考: 如果有多个重复的值,是否可以考虑用二分查找找到最后一个插入位置;(yahoo面试题目),主要考虑当有多个值是如何停止,避免进入死循环。

  1. public int searchInsert(int[] A, int target) {
  2. int len = A.length;
  3. if(len==0) return 0;
  4. int st = 0;
  5. int en = len-1;
  6. while(st<=en) {
  7. int mid = st + (en-st)/2;
  8. if(A[mid] == target) return mid;
  9. if(A[mid] < target) {
  10. st = mid + 1;
  11. } else {
  12. en = mid - 1;
  13. }
  14. }
  15. return st;
  16. }

多个重复元素算法:

     注意事项:要对1个或者2个元素进行边界控制,否则会无限循环。 其次要注意start和end的变化

     测试用例:int a[] = {1,2,3,4,4,4,4,4,4,4}; 返回10;

     start,mid,end; 当只有两个元素时或者之后一个元素时,要控制判断一下。

  1. int searchInsert(int A[],int target,int start,int end) {
  2.     if(start>end) return 0;
  3.     while(start<=end) {
  4.         int mid = start + (end-start)/2;
  5.         if(A[mid]==target) {
  6.             if(end - start <=1) {
  7.                  if(A[end] == target) return end+1;
  8.                  else 
  9.                      return start+1; 
  10.             } else {
  11.                 int result = insert(A,target,mid,end);
  12.                 return result;
  13.             }   
  14.         } else if(A[mid] < target) {
  15.             start = mid + 1 ; 
  16.         } else {
  17.             end = mid -  1;  
  18.         }                                                                     
  19.     }   
  20.     return start;
  21. }
posted @ 2014-07-02 21:27  purejade  阅读(87)  评论(0)    收藏  举报