Search Insert Position

来源:互联网 发布:最短路径算法有 编辑:程序博客网 时间:2024/04/28 14:47

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

答案

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. public class Solution { 
  2.     public int searchInsert(int[] A,int target) { 
  3.         if(target<=A[0]) 
  4.         { 
  5.             return 0
  6.         } 
  7.         if(target>A[A.length-1]) 
  8.         { 
  9.             return A.length; 
  10.         } 
  11.         int start=0
  12.         int end=A.length-1
  13.         while(start<=end) 
  14.         { 
  15.             int middle=start+(end-start)/2
  16.             if(A[middle]==target) 
  17.             { 
  18.                 return middle; 
  19.             } 
  20.             else 
  21.             { 
  22.                 if(target>A[middle]) 
  23.                 { 
  24.                     if(target<=A[middle+1]) 
  25.                     { 
  26.                         return middle+1
  27.                     } 
  28.                     start=middle+1
  29.                 } 
  30.                 else 
  31.                 { 
  32.                     if(target>A[middle-1]) 
  33.                     { 
  34.                         return middle; 
  35.                     } 
  36.                     end=middle-1
  37.                 } 
  38.                  
  39.             } 
  40.         } 
  41.         return 0
  42.     } 

0 0