标签:
原题链接在这里: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