zoukankan      html  css  js  c++  java
  • 【题解】【数组】【查找】【Leetcode】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

    思路:

    其实二分查找是最基本的,本来没什么可说的,要命的是谈虎色变,条件稍微一变,一紧张边界情况就想不清楚大脑内存耗尽,Search a 2D Matrix的时候,调了半天才发现程序是在二分处理只有两个元素的时挂了,写Median of Two Sorted Arrays的时候,又发现如果只有两个元素可能会造成死循环,所以担惊受怕的某程序媛决定采用这样的保守写法,小心地呵护trivial case,慎而试run之,大惊Accept

     1 int searchInsert(int A[], int n, int target) {
     2     int s = 0;
     3     int e = n-1;
     4     while(s < e-1 ){
     5         int mid = (s+e)/2;
     6         if(target == A[mid]){
     7             return mid;
     8         }else if(target > A[mid]){
     9             s = mid + 1;
    10         }else if(target < A[mid]){
    11             e = mid - 1;
    12         }
    13     }
    14     if(s == e-1){
    15         if(target <= A[s]) return s;
    16         else if(target > A[s+1]) return s+2;
    17         else return s+1;
    18     }else if(s == e){
    19         if(target <= A[s]) return s;
    20         else return s+1;
    21     }
    22 }

    为了不愧对大脑内存正常的同学,奉上干货Matrix67的两篇文章《漫话二分》,并贴出一种正常的写法。。。跟经典的二分查找相比,只是多了一个条件:

     1 int searchInsert(int A[], int n, int target) {  
     2   int l = 0, r = n-1;  
     3   while(l <= r){  
     4     int mid = (l+r)/2;  
     5     if(target == A[mid]) 
     6         return mid;
     7     if(mid > l && target < A[mid] && target > A[mid-1])//比二分查找仅仅多了这句
     8         return mid;
     9         
    10     if(target < A[mid]){  
    11       r = mid-1;
    12     }else{  
    13       l = mid+1;
    14     }     
    15   }  
    16   return l;  
    17 }  

     

  • 相关阅读:
    如何制定一周工作计划
    如何评估工作offer(1)
    Iraq shoethrower inspires Web games
    数据加密技术
    数字签名技术原理
    [转载]CSS使用技巧大全
    数字签名介绍
    数字签名原理剖析
    6个有用的MySQL语句
    PGP概述及原理
  • 原文地址:https://www.cnblogs.com/wei-li/p/3546644.html
Copyright © 2011-2022 走看看