- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
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
// 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.
int pos(vector<int> &arr, int x)
{
for(int i=0; i<arr.size(); i++)
{
if(arr[i]>=x)
return i;
}
return arr.size();
}
int pos2(vector<int> &arr, int x)
{
return lower_bound(arr.begin(), arr.end(), x)-arr.begin();
}
int pos3(vector<int> &arr, int x)
{
if(arr.empty()) return 0;
if(arr[0] >= x) return 0;
if(arr.back() < x) return arr.size();
int l=0, h=arr.size();
while(l<h-1)
{
int mid = l + (h-l)/2;
if(arr[mid]>=x)
h=mid;
else
l=mid+1;
}
return l;
}
447

被折叠的 条评论
为什么被折叠?



