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.

  • 相关阅读:
    Unix环境中的刷新
    C++ 的类型转换方法
    系统对信号的三种处理方式
    进程原语与线程原语的比较
    C和C++对带空参数列表的函数声明的不同处理
    函数指针
    字符串化的预处理器特征
    调试技巧
    信号产生的条件
    结构体大小问题
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086500.html
Copyright © 2011-2022 走看看