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.

  • 相关阅读:
    php 获取机器名
    php缓存参数祥解
    ajax参数祥解
    php 正则匹配返回字符串
    TP5验证规则使用
    J
    j
    virtualBox 桥接网卡 未指定
    Spring Cloud Alibaba基础教程:Nacos配置的加载规则详解
    Spring Cloud Alibaba基础教程:使用Nacos作为配置中心
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086500.html
Copyright © 2011-2022 走看看