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

LC.35.Search Insert Position

时间:2018-03-17 10:45:37      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:duplicate   return   cat   ted   pos   color   leetcode   post   sea   

https://leetcode.com/problems/search-insert-position/description/
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.

Example 1:

Input: [1,3,5,6], 5
Output: 2
Example 2:

Input: [1,3,5,6], 2
Output: 1
Example 3:

Input: [1,3,5,6], 7
Output: 4
Example 1:

Input: [1,3,5,6], 0
Output: 0

time complexity: o(logn)
space complexity: o(1)

 1     public int searchInsert(int[] nums, int target) {
 2         if (nums == null || nums.length ==0) return 0 ;
 3         int left = 0, right = nums.length -1 ;
 4         //corner case:
 5         if (nums[left]>target){
 6             return left ;
 7         }
 8         if (nums[right]<target){
 9             return right + 1 ;
10         }
11         while(left + 1 < right){
12             int mid = left + (right - left )/2 ;
13             if (nums[mid] == target) return mid ;
14             else if(nums[mid]<target){
15                 left = mid ;
16             } else {
17                 right = mid ;
18             }
19         }
20         //== now: 1) still have not found it 2) left and right sits right next to each other
21         //post processing
22         if (nums[left] == target) {
23             return left ;
24         }
25         if (nums[right] == target){
26             return right;
27         }
28         //remember left and right next to each other
29         if(nums[left]<target && target < nums[right]){
30             return left + 1 ;
31         }
32         return -1 ;
33     }

 




LC.35.Search Insert Position

标签:duplicate   return   cat   ted   pos   color   leetcode   post   sea   

原文地址:https://www.cnblogs.com/davidnyc/p/8587035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!