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         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(A == null || A.length == 0 || target < A[0]) return 0;
 5         int len = A.length;
 6         for(int i = 0; i < len; i ++){
 7             if(A[i] == target){
 8                 return i;
 9             }
10             else if(A[i] > target){
11                 return i;
12             }
13         }
14         return len;
15     }
16 }

 第二遍:

采用二分来做。

 1 public class Solution {
 2     public int searchInsert(int[] A, int target) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(A == null || A.length == 0 || target < A[0]) return 0;
 5         int len = A.length;
 6         int start = 0;
 7         int end = len - 1;
 8         int ret = end;
 9         while(start <= end){
10             int mid = (start + end) / 2;
11             if(target == A[mid]) return mid;
12             if(target < A[mid]){
13                 ret = mid;
14                 end = mid - 1;
15             }else{
16                 ret = mid + 1;
17                 start = mid + 1;
18             }
19         }
20         return ret;
21     }
22 }

 

posted on 2013-10-12 12:55  Step-BY-Step  阅读(142)  评论(0编辑  收藏  举报

导航