[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; }