标签:
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 static int searchInsert(int[] A, int target) { 3 if (A.length == 0 || A == null) 4 return -1; 5 int start = 0; 6 int end = A.length - 1; 7 8 while (start + 1 < end) { 9 int mid = start + (end - start) / 2; 10 if(A[mid] == target) 11 return mid; 12 else if(A[mid] < target) 13 start = mid; 14 else 15 end = mid; 16 } 17 18 System.out.println("start:" + start + "end:" + end); 19 20 if (A[end] == target) { 21 return end; 22 } 23 if (A[end] < target) { 24 return end + 1; 25 } 26 if (A[start] == target) { 27 return start; 28 } 29 return start + 1; 30 } 31 32 public static void main(String[] args) { 33 System.out.println(searchInsert(new int[]{1,3,5,6}, 4)); 34 } 35 }
https://oj.leetcode.com/problems/search-insert-position/
标签:
原文地址:http://www.cnblogs.com/luochuanghero/p/4280572.html