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/

  • 相关阅读:
    linux apache + mysql +php no-yum
    linux apache + mysql +php
    1像素border
    vue-router配置
    错误Cannot find module 'stylus'
    高仿饿了么mock本地数据
    vue2.0高仿饿了么better-scroll
    npm 常用命令
    Gulp工具常用插件
    git总结
  • 原文地址:https://www.cnblogs.com/hygeia/p/4779852.html
Copyright © 2011-2022 走看看