【Leetcode】【Medium】Search Insert Position

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

解题思路:

典型的二分查找应用,注意数组下标为0~n-1,但是可能数字需要插在数组最后第n的位置上。

由于需要找到一个大于等于target数所在的位置,进行插入;所以当nums[mid] > target时,r应该等于mid;因此采用 mid=(l+r)/2,l=mid+1的组合;

对于二分查找有兴趣的同学,可以看另一道Leetcode题目Search for a Range,对二分查找的应用更加全面,在里面,我也写了一些自己学习二分查找总结的心得;

代码:

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         int l = 0;
 5         int r = nums.size();
 6         while (l < r) {
 7             int mid = (l + r) / 2;
 8             if (nums[mid] > target)
 9                 r = mid;
10             else if (nums[mid] == target) 
11                 return mid;
12             else
13                 l = mid + 1;
14         }
15         return r;
16     }
17 };
原文地址:https://www.cnblogs.com/huxiao-tee/p/4395539.html