首页 > 其他 > 详细

LeetCode Search Insert Position

时间:2015-10-15 09:49:41      阅读:216      评论:0      收藏:0      [点我收藏+]

原题链接在这里:https://leetcode.com/problems/search-insert-position/

题目是二分法查找,若是loop中找到了就返回mid, 若是没有找到,跳出loop时,恰巧l 会走到比target 大的index上,r会走到比target小的index上。

Time Complexity: O(log n), Space O(1).

AC Java:

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if(nums == null || nums.length == 0){
 4             return -1;
 5         }
 6         int l = 0;
 7         int r = nums.length - 1;
 8         while(l<=r){
 9             int mid = l+(r-l)/2;
10             if(nums[mid] == target){
11                 return mid;
12             }else if(nums[mid] < target){
13                 l = mid+1;
14             }else{
15                 r = mid-1;
16             }
17         }
18         return l;
19     }
20 }

 

LeetCode Search Insert Position

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4881316.html

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