题1:
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.
题2:如果允许上题的数组有重复数字呢?
解法:最笨的方法,也是最容易想到的方法就是直接遍历数组,找出最小值,时间复杂度O(n),但是对于本题明显会超时。此时,比较容易想到的就是二分查找,因为其有序。但是两者肯定是有不同点的。
第一题的代码如下:
public int findMin(int[] num) { int low = 0; int high = num.length-1; while (low < high-1) { int mid = low + (high-low)/2; if (num[low] < num[high]) { if (num[mid] < num[low]) { low = mid; } else { high = mid; } } else { if (num[mid] < num[high]) { high = mid; } else { low = mid; } } } return num[low] > num[high] ? num[high] : num[low]; }
此题一定要区分,这个序列是递增的还是递减的。很多解题方法都没考虑这个问题。显然有了第一题的思路,第二题也就好解了。
public int findMin(int[] num) { int low = 0; int high = num.length-1; while (low < high-1) { int mid = low + (high-low)/2; if (num[low] < num[high]) { if (num[mid] < num[low]) { low = mid; } else if (num[mid] > num[low]){ high = mid; } else { low++; } } else { if (num[mid] < num[high]) { high = mid; } else if (num[mid] > num[high]){ low = mid; } else { high--; } } } return num[low] > num[high] ? num[high] : num[low]; }
时间: 2024-11-08 20:06:24