- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Given a sorted array of strings which is interspersed with empty strings, write a meth-
od to ind the location of a given string.
Example: ind “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4
Example: ind “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1
/*
"at", "az", "", "", "ba", "", "bbb"
ba
"at", "az", "", "", "ba", "", "bbb"
a a a a a a a a b; find a
|
a a b b b b b b b; find a
|
[] [] [] [] ; find []
mid =
1. find the mid string
2. compare mid string with target
3. two cases: target < arr[mid] -> set l=mid
or target >= arr[mid] -> set u=mid
*/
bool compare(string &m, string &target)
{
return target < m;
}
int find(const vector<string> &arr, string &target)
{
int u=arr.size();
int l=0;
if(target=="")
{
for(int i=0; i<arr.size(); i++)
{
if(arr[i]=="") return i;
}
return -1; // can not find the target
}
while(l<u-1)
{
int mid = l + (u-l)/2;
// step forward to find the first non-empty
while(arr[mid].empty())
{
if(mid==u) break;
mid++;
}
// If there is no non-empty string forward
if(mid==u)
{
mid = l + (u-l)/2;
while(arr[mid].empty())
{
if(mid==-1) return -1; // can not find target.
mid--;
}
}
bool rst = compare(arr[mid], target);
if(rst) // target < arr[mid]
{
l = mid-1;
}
else
{
u = mid;
}
}
if(arr[l] == target)
{
return l;
}
else
return -1;
}