public class Solution { /** * @param num: a rotated sorted array * @return: the minimum number in the array */ public int findMin(int[] num) { // write your code here // handle corner case // the idea is to find the [first] element less than num[num.length - 1] if (num == null || num.length == 0) { return -1; } int start = 0, end = num.length - 1; int target = num[end]; while (start + 1 < end) { int mid = start + (end - start) / 2; int current = num[mid]; if (current > target) { start = mid; } else { end = mid; } } // decide which to choose if (num[start] < target) { return num[start]; } return num[end]; } }
使用二分搜索来做,基本思想就是: find the first element less than num[num.length - 1],至于为什么要这样,画个图就知道了后一段的数肯定要比前一段的数小。
时间: 2024-09-30 06:07:21