• 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/

  • 相关阅读:
    地铁线路问题分析
    软件工程大作业(社团管理系统)-个人总结报告
    第九组_社团管理系统_原型相关文档
    北京地铁线路出行和规划
    地铁线路规划
    WC 个人项目 ( node.js 实现 )
    自我介绍 + 软工5问
    软工个人项目(Java实现)
    自我介绍+软工五问
    结对编程(前后端分离)
  • 原文地址:https://www.cnblogs.com/hygeia/p/4779852.html
Copyright © 2020-2023  润新知