Find Minimum in Rotated Sorted Array

 package leetcode;
/* *
* 注意问题:
* 1. 原序列升序、降序问题,两种情况都要考虑
* 2. 边界问题,如果只有两个元素时要单独考虑,在num[mid]==num[left]判断中考虑
* 3. 采用2叉查找的思想
* */
public class findMinInRotatedSortedArray {
public int findMin(int[] num)
{ int left=0;
int right=num.length-1;
if(num[left]>num[right])//原序列是升序排列
{
while(left < right)
{
int mid=(left+right)/2;
if(num[mid]==num[left])
left=mid+1;
else if(num[mid]>num[left])
left=mid;
else
right=mid; }
}
else //原序列是降序排列
{
while(left < right)
{
int mid=(left+right)/2;
if(num[mid]==num[left])
right=mid-1;
else if(num[mid]>=num[left])
right=mid;
else
left=mid;
}
}
return num[left];
}
public static void main(String[] args)
{
int[] arr=new int[3];
arr[0]=3;
arr[1]=1;
arr[2]=2;
findMinInRotatedSortedArray a=new findMinInRotatedSortedArray();
System.out.println(a.findMin(arr));
}
}
上一篇:linux清华源配置


下一篇:macOS Monterey 12.12.2 (21D49) 正式版 ISO、IPSW、PKG 下载