面试问题: 已旋转已排序的数组,以便元素可能以3456712的顺序出现。您如何找到最小元素?您可以假设该数组具有所有唯一元素
需要实现修改的二进制搜索算法。 C ++中的第一个(不正确的解决方案):
int findMin(int a[], unsigned int leftIndex, unsigned int rightIndex)
{
while(leftIndex <= rightIndex)
{
unsigned int mid = leftIndex + (rightIndex - leftIndex) / 2;
if(leftIndex == rightIndex) return a[rightIndex];
if(a[rightIndex] > a[mid] && a[leftIndex] > a[mid])
{
++leftIndex;
rightIndex = mid;
}
if(a[rightIndex] > a[mid]) rightIndex = --mid;
if(a[rightIndex] < a[mid]) leftIndex = ++mid;
}
}
Java中的第二个实现,即在已排序的数组中查找最小值。它通过了单元测试。如果您在Java实现中找到它们,请告诉我有关错误的信息。
class Test
{
static public int findMin(int a[], int leftIndex, int rightIndex)
{
while(leftIndex <= rightIndex)
{
int mid = leftIndex + (rightIndex - leftIndex) / 2;
if(leftIndex == rightIndex) return a[rightIndex];
if(rightIndex - leftIndex == 1) return Math.min(a[leftIndex], a[rightIndex]);
if(a[rightIndex] > a[mid]) rightIndex = mid;
if(a[rightIndex] < a[mid]) leftIndex = mid;
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception
{
int a1 [] = {1};
System.out.println(findMin(a1,0,0));
int a2 [] = {1,2};
int a3 [] = {2, 1};
System.out.println(findMin(a2,0,1));
System.out.println(findMin(a3,0,1));
int a4 [] = {1, 2, 3};
int a5 [] = {2, 3, 1};
int a6 [] = {3, 1, 2};
System.out.println(findMin(a4,0,2));
System.out.println(findMin(a5,0,2));
System.out.println(findMin(a6,0,2));
int a7 [] = {1, 2, 3, 4};
int a8 [] = {2, 3, 4, 1};
int a9 [] = {3, 4, 1, 2};
int a10 [] = {4, 1, 2, 3};
System.out.println(findMin(a7,0,3));
System.out.println(findMin(a8,0,3));
System.out.println(findMin(a9,0,3));
System.out.println(findMin(a10,0,3));
}
}
Java中的递归实现:
static public int findMin(int a[], int leftIndex, int rightIndex)
{
int mid = leftIndex + (rightIndex - leftIndex) / 2;
if(leftIndex == rightIndex) return a[rightIndex];
if(rightIndex - leftIndex == 1) return Math.min(a[leftIndex], a[rightIndex]);
if(a[rightIndex] > a[mid]) return findMin(a, leftIndex, mid);
if(a[rightIndex] < a[mid]) return findMin(a, mid, rightIndex);
return -1;
}