• 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     }
  • 相关阅读:
    Python学习笔记 第四天
    Python学习笔记 第三天
    linux系统优化(CentOS7)
    ARMS踩坑合集
    zabbix报错合集(附解决方法)
    keepalived
    ansible
    nginx
    安装虚拟机
    linux发展、redhat与centos的区别
  • 原文地址:https://www.cnblogs.com/mike442144/p/3480269.html
Copyright © 2020-2023  润新知