- 首先我要在纸上,非常非常聪明且迅速且机灵,
- 给出几个用例,找出边界用例和特殊用例,确定特判条件;在编码前考虑到所有的条件
- 向面试官提问:问题规模,特殊用例
- 给出函数头
- 暴力解,简述,优化。
- 给出能够想到的最优价
- 伪代码,同时结合用例
- 真实代码
Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
bool in(vector<int> &arr, int l, int h, int x)
{
if(arr[l]<arr[h])
return x>=arr[l] && x<=arr[h];
else
return x>=arr[l] || x<=arr[h];
}
int search(vector<int> &arr, int x)
{
int l=0, h=arr.size();
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 l;
else return -1;
}
修正版:
class Solution {
public:
int 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 l;
if(arr[h]==x) return h;
else return -1;
}
bool in(int arr[], int l, int h, int x)
{
if(arr[l]<arr[h])
return x>=arr[l] && x<=arr[h];
else
return x>=arr[l] || x<=arr[h];
}
};
搜索旋转排序数组的高效算法
本文详细介绍了如何解决在已排序数组经过旋转后搜索特定元素的问题,通过优化边界用例和实现高效的搜索函数,确保在不同场景下都能快速找到目标值。
832

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



