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.

  • 相关阅读:
    Grid布局方式
    布局
    应用主题资源
    主题资源
    返回键
    标记 {x:Null},d:DesignWidth,d:DesignHeight
    WMAppManifest.xml
    项目模板
    Panorama和Pivot控件
    ashx页面中context.Session["xxx"]获取不到值的解决办法
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086500.html
Copyright © 2011-2022 走看看