- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Search in Rotated Sorted Array II
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
class Solution {
public:
bool search(int arr[], int n, int x)
{
int l=0, h=n-1;
while(l<h-1)
{
int m = l+(h-l)/2;
if(in(arr, l, m, x))
h=m;
else
l=m+1;
}
if(arr[l]==x) return true;
if(arr[h]==x) return true;
else return false;
}
bool in(int arr[], int l, int h, int x)
{
if(arr[l]<arr[h])
return x>=arr[l] && x<=arr[h];
else if (arr[l]>arr[h])
return x>=arr[l] || x<=arr[h];
else
// 1 1 1 1 1 1 [1] 1 1 3 1 1
// 1 1 1 3 1 1 1 [1] 1 1 1 1
{
if(x==arr[l]) return true;
while(l<h && arr[l] == arr[h])
l++;
if(l==h) return false;
return in(arr, l, h, x);
}
}
};