- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
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);
}
}
};
本文深入探讨了在旋转排序数组中搜索目标元素的算法,特别关注允许重复元素的情况。通过引入边界用例和特殊用例分析,详细解释了优化搜索过程,并提供了相应的伪代码实现。重点阐述了如何处理重复元素,从而影响运行时间复杂度,并给出了优化策略。
1933

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



