• [LeetCode] 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
    » Solve this problem

    [解题思路]
    跟经典的二分查找相比,只是多了一个条件:
    if(mid>left && A[mid]>target && A[mid-1]<target)


    [Code]
    1:  int searchInsert(int A[], int n, int target) {  
    2: // Start typing your C/C++ solution below
    3: // DO NOT write int main() function
    4: int l=0, r=n-1;
    5: while(l<=r)
    6: {
    7: int mid = (l+r)/2;
    8: if(A[mid] == target) return mid;
    9: if(mid>l && A[mid]>target && A[mid-1]<target ) return mid;
    10: if(A[mid] > target)
    11: {
    12: r= mid-1;
    13: }
    14: else
    15: {
    16: l=mid+1;
    17: }
    18: }
    19: return l;
    20: }







  • 相关阅读:
    抽象工厂模式
    工厂方法模式
    单例模式
    适配器模式
    外观模式
    简单工厂模式
    设计模式开篇闲谈
    android ui更新
    android获取Context
    android 事件绑定
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078955.html
Copyright © 2020-2023  润新知