标签:
题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]; }
LeetCode-Find Minimum in Rotated Sorted Array(找出反转数组中的最小值)
标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/44114951