Search Insert Position

来源:互联网 发布:java如何合并两个list 编辑:程序博客网 时间:2024/04/27 14:47

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


题目解析:

(1)利用二分查找,时间复杂度为O(n*logn)。

(2)注意一些边界条件,当target < A[0]时候,返回为0,当target > A[n-1]的时候返回为n。

#include <iostream>using namespace std; int searchInsert(int A[], int n, int target) {int begin = 0;int end = n-1;if(target < A[0])return 0;if(target > A[n-1])return n;if(n==0)exit(1);while(begin < end){int mid = (begin+end)/2;if(A[mid] == target)return mid;if(A[mid] > target){end = mid - 1;}if(A[mid] < target){begin = mid + 1;}}if(target > A[end])return end+1;if(target <= A[end])return end;}int main(void){int A[] = {1,3};cout << searchInsert(A, 2, 0) << endl; system("pause");return 0;}


0 0
原创粉丝点击