153 Find Minimum in Rotated Sorted Array
链接:https://leetcode.com/problemset/algorithms/
问题描述:
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.
Hide Tags Array Binary Search
这题就是求给出数组中的最小元素,但是给出的数组是有规律的。如将整个数组排序后找最小元素,在C语言实测中用二分法排序是可以AC的:
int cmp(const void *a, const void *b)
{
return(*(int *)a-*(int *)b);
}
int findMin(int* nums, int numsSize) {
if(nums==NULL)
return 0;
qsort(nums,numsSize,sizeof(int),cmp);
return nums[0];
}
因为这里给出的数组是有一定顺序的,只是可能有且只有一个位置数组排序顺序出现错误。因此采用二分搜索可以更好地解决这个问题,采用二分法查找时,数据需是排好序的。
class Solution {
public:
int findMin(vector<int>& nums) {
int length=nums.size();
int i=0,k=length/2,j=length-1;
while(true)
{
if(k==j)
return nums[i]>nums[k]?nums[k]:nums[i];
if(nums[k]-nums[i]<k-i)
{
length=k-i+1;
k=length/2+i;
j=i+length-1;
}
else if(nums[j]-nums[k]<j-k)
{
length=j-k;
i=k+1;
k=length/2+i;
}
else
{
return nums[i];
}
}
}
};
二分法的主要思想是:(设查找的数组区间为array[low, high])(1)确定该期间的中间位置K(2)将查找的值T与array[k]比较。若相等,查找成功返回此位置;否则确定新的查找区域,继续二分查找。区域确定如下:a.array[k]>T 由数组的有序性可知array[k,k+1,……,high]>T;故新的区间为array[low,……,K-1]b.array[k]