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
二分法:
#include <iostream> using namespace std; int find2(int *a,int n,int num) { int low=0,high=n-1; while(low<=high) { int mid=(low+high)/2; if(a[mid]<num) low=mid+1; else if(a[mid]>num) high=mid-1; else return mid; } return low; } int main() { int a[]={1,3,5,6}; int num=2,n=4; cout<<find2(a,n,num); }
another
class Solution { public: int searchInsert(int A[], int n, int target) { return find(A, 0, n, target); } int find(int A[], int start, int end, int target) { int p = end - start; if(p==1 || p==0) { if(A[start] >= target) return start; if(A[start] < target) return start+1; } int m = p / 2; if(A[start + m] == target) return start + m; if(A[start + m] > target) return find(A, start, start+m, target); else return find(A, start+m, end, target); } };