首页 > 代码库 > Search Insert Position

Search Insert Position

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             else20                 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