码迷,mamicode.com
首页 > 其他好文 > 详细

(35)Search Insert Position

时间:2015-02-08 23:14:45      阅读:176      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!