zoukankan      html  css  js  c++  java
  • [Leetcode 23] 35 Search Insert Position

    Problem:

    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

    Analysis:

    An variant of binary search. Pay special attention what to return when there's no match

    Time complexity is O(logn), space complexity is O(n)

    Code:

     1 public class Solution {
     2     public int searchInsert(int[] A, int target) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int lo = 0, hi = A.length-1;
     6         
     7         while (lo <= hi) {
     8             int mid = (lo + hi) / 2;
     9             
    10             if (A[mid] == target) {
    11                 return mid;
    12             } else if (A[mid] < target) {
    13                 lo = mid+1;
    14             } else { //(A[mid] > target)
    15                 hi = mid-1;
    16             }
    17         }
    18         
    19         return lo;
    20     }
    21 }
    View Code

    Attention:

    The insertion place is lo no lo+1 if there is no match. The reason is (lo+hi)/2 will always make mid towards the lo, then when while loop exits (now lo=hi), both lo and hi points to the element that is just less then target element.

  • 相关阅读:
    用户控件
    垃圾弟弟
    如何解决“呈现控件时出错”的问题
    IE与FireFox差距
    NavigateUrl属性绑定
    table
    firefox不支持attachEvent,attach
    转 jQuery分类 
    GridView列数字、货币和日期的显示格式
    appendChild
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086500.html
Copyright © 2011-2022 走看看