zoukankan      html  css  js  c++  java
  • Search Insert Position [LeetCode]

    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

    Summary: basic binary search stuff.

     1     int searchInsert(int A[], int n, int target) {
     2         int start = 0;
     3         int end = n - 1;
     4         while(start <= end) {
     5             int median = start + (end - start + 1) / 2;
     6             if(target == A[median]) {
     7                 return median;
     8             }else if(target < A[median]) {
     9                 if(median - 1 >= 0 && target > A[median - 1])
    10                     return median;
    11                 if(median == 0)
    12                     return 0;
    13                 end = median - 1;
    14             }else {
    15                 if(median + 1 <= n - 1 && target < A[median + 1])
    16                     return median + 1;
    17                 if(median == n - 1)
    18                     return n;
    19                 start = median + 1;
    20             }
    21         }
    22     }
  • 相关阅读:
    手机自动化
    记录
    Linux 死机了怎么办
    前端源码
    LNMP环境
    PHP学习之路(一)
    py
    蜘蛛问题
    mongodb
    【HTML/XML 2】XML基础知识点总结
  • 原文地址:https://www.cnblogs.com/guyufei/p/3425325.html
Copyright © 2011-2022 走看看