zoukankan      html  css  js  c++  java
  • [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: }







  • 相关阅读:
    关于Unity中资源打包
    关于Unity中的物理
    关于Unity中特殊目录
    关于Unity中脚本
    千八行
    早春游园
    西湖冬景
    七尖行
    黄山游记
    四季
  • 原文地址:https://www.cnblogs.com/codingtmd/p/5078955.html
Copyright © 2011-2022 走看看