153. Find Minimum in Rotated Sorted Array
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
solution :
首先利用binary search求得pivot的位置。
题目解法关键在于找到lo和hi以后如何确定pivot
举例:origi_nums = [1,3,5]
nums = [5,1,3] 很明显此时 pivot =1, 首先比较 nums[lo]和nums[hi]的大小,如果nums[lo] < nums[hi]说明整个数组都是顺序正确的,没有pivot,于是给pivot赋值0;反之如果nums[lo] > nums[hi],说明pivot存在,且就在lo和hi之间,于是给pivot赋值hi。
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) return -1;
if (nums.length == 1) return nums[0];
int lo = 0;
int hi = nums.length - 1;
// find the pivot
// [4, 5, 6, 7, | 0, 1, 2]
while (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] > nums[lo]) {
lo = mid;
} else if (nums[mid] < nums[lo]) {
hi = mid;
}
}
// (index in sorted array + hi)%nums.length = index in rotated array
int pivot = (nums[lo] > nums[hi]) ? hi:0;
return nums[pivot];
}
154. Find Minimum in Rotated Sorted Array II
154题目区别在于数组中允许出现duplicates。
第一次尝试写出来的代码有点问题
class Solution {
public int findMin(int[] nums) {
if (nums == null || nums.length == 0) return -1;
if (nums.length == 1) return nums[0];
int thres = nums[nums.length - 1];
int lo = 0;
int hi = nums.length - 1;
int pivot = 0;
while (lo + 1 < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < thres) {
hi = mid;
} else if (nums[mid] > thres) {
lo = mid;
} else if (nums[mid] == thres) {
hi--;
}
}
if (nums[lo] >= thres) {
pivot = hi;
}
return nums[pivot];
}
}
solution
class Solution {
public int findMin(int[] nums) {
int low = 0, high = nums.length - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
if (nums[pivot] < nums[high])
high = pivot;
else if (nums[pivot] > nums[high])
low = pivot + 1;
else
high -= 1;
}
return nums[low];
}
}