153. Find Minimum in Rotated Sorted Array

22次阅读

共计 902 个字符,预计需要花费 3 分钟才能阅读完成。

Suppose an array sorted in ascending order 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.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0

难度:medium
题目:假设一个按升序排序的数组在某个未知的轴上旋转。假定数组中没有重复元素。
思路:分情况二叉搜索

Runtime: 0 ms, faster than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array.Memory Usage: 37.6 MB, less than 100.00% of Java online submissions for Find Minimum in Rotated Sorted Array.
class Solution {
public int findMin(int[] nums) {
return findMin(nums, 0, nums.length – 1);
}

public int findMin(int[] nums, int left, int right) {
int mid = left + (right – left) / 2;
// 升序
if (nums[left] <= nums[mid] && nums[mid] <= nums[right]) {
return nums[left];
}
// 降序
if (nums[left] >= nums[mid] && nums[mid] >= nums[right]) {
return nums[right];
}
// 升序占大降序占小
if (nums[left] >= nums[mid]) {
return findMin(nums, left, mid);
}
// 升序占小降序占大
return findMin(nums, mid, right);
}
}

正文完
 0