[LeetCode] 35. 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

问题:给定一个已排序数组和一个整数,若整数已在数组中则返回在数组中的下标,否则返回应当插入的位置。

对一个已排序数组进行搜索,很自然地会想到二分搜索(Binary Search),毕竟是经典场景。这道题也确实是二分搜索的一个简单应用。

之所以记录这道题目,是感觉二分搜索和之前做的 双指针法 two pointers ,或者是滑动窗口算法(sliding window) 有些相似。

二分搜索,实际上,可以理解为每次减半的滑动窗口算法,来定位最终的目标位置。

而滑动窗口算法,另一个典型场景就是求解最大/最小 的连续子数组,或连续子字符串。在另一篇博文有介绍:Minimum Size Subarray Sum 。

 1 int searchInsert(vector<int>& nums, int target) {
 2     
 3     if (nums.size() == 0) {
 4         return 0;
 5     }
 6     
 7     if (nums.size() == 1) {
 8         return (nums[0] < target) ? 1 : 0;
 9     }
10     
11     
12     int l = 0;
13     int r = (int)nums.size() - 1;
14     
15     while (l < r) {
16         
17         if (l + 1 == r) {
18             if ( target <= nums[l]) {
19                 return l;
20             }
21             else if (target <= nums[r]){
22                 return r;
23             }
24             else{
25                 return r+1;
26             }
27         }
28         
29         int mid = (l + r) / 2;
30         
31         if (nums[mid] == target) {
32             return mid;
33         }
34         
35         if (nums[mid] < target) {
36             l = mid;
37         }else{
38             r = mid;
39         }
40     }
41     
42     // 实际上无法执行到这里,在前面必然有 return.
43     return 0;
44 }
原文地址:https://www.cnblogs.com/TonyYPZhang/p/5077813.html