$$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Self-defined math definitions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Math symbol commands \newcommand{\intd}{\,{\rm d}} % Symbol 'd' used in integration, such as 'dx' \newcommand{\diff}{{\rm d}} % Symbol 'd' used in differentiation ... $$

35. 搜索插入位置

题目描述查看:https://leetcode-cn.com/problems/search-insert-position/

  题目的意思是从一个有序的数组中,查找一个数,并且这个数如果有可能不存在,不存在返回插入位置index。

  • 思路

二分查找,如果没找着,就判断是left指针破坏了循环,还是right指针破坏了循环。

  • 边界条件

如果没找着,意味着left > right了,此时left的位置是插入位置。

 1 public static int searchInsert(int[] nums, int target) {
 2     if(nums.length == 0)return 0;
 3     int left = 0;
 4     int right = nums.length-1;
 5     while(left <= right){
 6         int mid = left +(right - left)/2;
 7         if(nums[mid] == target)return mid;
 8         else if(nums[mid] > target)right = mid - 1;
 9         else
10             left = mid +1;
11     }
12     if(left > right)return left;
13     else
14         return right;
15 }

 

posted @ 2020-03-28 22:00  V丶vvv  阅读(240)  评论(0编辑  收藏  举报