zoukankan      html  css  js  c++  java
  • [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 }
  • 相关阅读:
    严援朝座右铭
    王治郅 请让爱国走下神坛
    Java 事件处理实例
    SAP ERP 与 Oracle ERP 比较
    Gantt Component for Delphi Pure Pascal code(TsyGantt VCL)
    XMLRPC vs. SOAP
    Interfaces with Constants Only(java中通用常量定义)
    船舶设计软件简介
    DelphiARX 2000i 简介
    JAVA事件适配器用内部类,匿名类实现事件处理
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5077813.html
Copyright © 2011-2022 走看看