zoukankan      html  css  js  c++  java
  • 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.

    Example

    [1,3,5,6], 5 → 2

    [1,3,5,6], 2 → 1

    [1,3,5,6], 7 → 4

    [1,3,5,6], 0 → 0

    Challenge

    O(log(n)) time

    Solution 1

     Naively, we can just iterate the array and compare target with ith and (i+1)th element. Time complexity is O(n)

     1 public int searchInsert(int[] A, int target) 
     2     {
     3         // write your code here
     4      if(A.length==0) return 0;
     5  
     6         if(target <= A[0]) return 0;
     7  
     8         for(int i=0; i<A.length-1; i++){
     9             if(target > A[i] && target <= A[i+1]){
    10                 return i+1;
    11             }
    12         }
    13  
    14         return A.length;
    15         
    16     }

    Solution 2

     This also looks like a binary search problem. We should try to make the complexity to be O(log(n)).

     1     public int searchInsert(int[] A, int target) 
     2     {
     3         // write your code here
     4      if(A.length==0) return 0;
     5      return helper(A, target, 0, A.length-1);
     6         
     7     }
     8     
     9     
    10     public int helper(int[] A, int target, int start, int end)
    11     {
    12         int mid = (start+end)/2;
    13         
    14         if (target == A[mid]) return mid;
    15         
    16         if(target<A[mid])
    17         {
    18             if (mid <= start) return start;
    19             else
    20             {
    21                 return helper(A,target,start,mid-1);
    22             }
    23         }
    24         
    25         else  //target > A[mid]
    26         {
    27             if(mid >= end) return end+1;
    28             else
    29             {
    30                 return helper(A,target,mid+1,end);
    31             }
    32         }
    33         
    34         
    35     }

    reference: http://www.programcreek.com/2013/01/leetcode-search-insert-position/

  • 相关阅读:
    05流程图和流程定义的操作
    04启动流程实例,任务的查询与完成
    03流程图的绘制与部署
    02数据库表的初始化方式
    01环境安装
    JavaScript基础和JavaScript内置对象:
    用手机、pid作为win电脑扩展屏
    H5新增特性之语义化标签
    盒模型
    CSS定位总结--static、relative、absolute、fixed
  • 原文地址:https://www.cnblogs.com/hygeia/p/4779852.html
Copyright © 2011-2022 走看看