题目:
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
).
Find the minimum element.
You may assume no duplicate exists in the array.
思路:
一开始看错题目,以为是求一趟排序的轴值,于是想到利用快排。代码如下:
public class Solution {
//利用快排求一趟排序轴值
public static int findMin(int[] num) {
int p,i,j;
p = num[0] ;//轴值
i = 0;
j = num.length-1;
while(i < j)
{
while(i < j && num[j] >= p)
{
j--;
}
num[i] = num[j];
while(i < j && num[i] <= p)
{
i++;
}
num[j] = num[i];
}
num[i] = p;
System.out.print("\n一趟排序后:");
for(int x =0 ; x < num.length ; x++)
System.out.print(" " +num[x]);
return i;
}
public static void main(String[] args){
int[] n = new int[]{49,14,38,74,96,65,8,49,55,27};
System.out.print("待排序数: ");
for(int x =0 ; x < n.length ; x++)
System.out.print(" "+n[x]);
System.out.println("\n一趟排序的轴值是:"+ Solution.findMin(n));
}
}
仔细读题,看到关键词 a sorted array 、 is rotated、 at some pivot unknown to you beforehand.
还是没注意到the minimum element.是最小值的意思,即使此时我用有道翻译,知道前几个关键词理解错了,这个minimum我查到是最小值,但是我任然以为是求最中间的值。于是想到折半插入排序,然后遍历最终数组得到中间值。代码如下:
public class SolutionBinarySort{
//利用折半查找求有序表数组的中间值
public static int findMin(int[] num) {
int high,low,i,j,mid,p;
for(i = 1; i <= num.length-1; i++)
{
p = num[i];
low = 0;
high = i -1 ;
while(low <= high)
{
mid = (low + high)/2;
if(num[i] >= num[mid])
{
low = mid + 1;
}
else
high = mid -1;
}
for(j = i -1; j >= high +1; j--)
{
num[j+1] = num[j];
}
num [high +1] = p;
}
System.out.print("\n折半排序后: ");
for(int x =0 ; x < num.length ; x++)
System.out.print(" " +num[x]);
return num[(num.length-1)/2];
}
public static void main(String[] args)
{
int a[] = new int[]{5,7,4,9,3};
//int a[] = new int[]{1,2,3};
System.out.print("待排序数: ");
for(int x =0 ; x < a.length ; x++)
System.out.print(" " +a[x]);
System.out.print("\n中间值是 " + findMin(a));
}
}
最后,实在受不了了,用有道翻译,改了最后的返回值return num[0],拉倒了就。最终ac runtime 412ms.