[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
Array Binary Search
这题其实便是二分搜索,需要考虑没有找到的时候的情况。
#include <iostream> using namespace std; class Solution { public: int searchInsert(int A[], int n, int target) { if(n==0) return 0; // if(target<=A[0]) return 0; if(A[n-1]<target) return n; int l=0,r=n-1,m=0; while(l<=r){ m=(l+r)/2; // cout<<l<<" "<<m<<" "<<r<<endl; if(A[m]==target) return m; if(A[m]<target) l=m+1; else r=m-1; } if(target<A[m]) return m; return m+1; } }; int main() { int a[]={1,3}; Solution sol; for(int i=0;i<=4;i++) cout<<i<<" "<<sol.searchInsert(a,sizeof(a)/sizeof(int),i)<<endl; return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步