zoukankan      html  css  js  c++  java
  • Search Insert Position

    题目:

    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

    这个题目比较简单,也就是二分作一些处理。代码:

     1     int searchInsert(int A[], int n, int target) {
     2         return binarySearch(A,0,n-1,target);
     3     }
     4     int binarySearch(int A[],int s,int e,int target){
     5         while(s<=e){
     6             int mid=s+(e-s)/2;
     7             if(A[mid]==target) return mid;
     8             if(s==e) return A[mid]>target?s:s+1;
     9             if(target<A[mid]) {
    10                 if(mid==s) return s;
    11                 e=mid-1;
    12             }
    13             else {
    14                 if(mid==e) return e+1;
    15                 s=mid+1;
    16             }
    17         }
    18     }
  • 相关阅读:
    yii中通过HTTP post接收
    网络编程
    python 异常处理
    面向对象(2)
    面向对象
    什么是模块精讲
    常用模块二
    各种推导式详解
    匿名函数
    迭代器生成器
  • 原文地址:https://www.cnblogs.com/mike442144/p/3480269.html
Copyright © 2011-2022 走看看