首页 > 其他 > 详细

(35)Search Insert Position

时间:2015-02-08 23:12:03      阅读:330      评论:0      收藏:0      [点我收藏+]

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/

(35)Search Insert Position

原文:http://www.cnblogs.com/luochuanghero/p/4280572.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!