题目要求:
给一个排序数组和待查找值,返回其在数组中的位置或待插入的位置,并确保数组中无重复值
示例:
[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<stdafx.h>
#include <iostream>
using namespace std;
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int low=0;
int cur=(n-1)/2;
int high=n-1;
while(low<=high)
{
if(target<A[cur])
{
high=cur-1;
cur=(high+low)/2;
}
else if(target>A[cur])
{
low=cur+1;
cur=(high+low)/2;
}
else
return cur;
}
if(target<A[cur])
{
if(cur==0)
{
return 0;
}
else
return cur-1;
}
else if(target>A[cur])
{
return cur+1;
}
}
};
void main()
{
int A[4]={1,3,5,6};
Solution s;
cout<<s.searchInsert(A,4,0)<<endl;
getchar();
}