Find Minimum in Rotated Sorted Array

 1 package leetcode;
 2 /* *
 3  * 注意问题:
 4  * 1. 原序列升序、降序问题,两种情况都要考虑
 5  * 2. 边界问题,如果只有两个元素时要单独考虑,在num[mid]==num[left]判断中考虑
 6  * 3. 采用2叉查找的思想
 7  * */
 8 public class findMinInRotatedSortedArray {
 9     public int findMin(int[] num)
10     {
11         
12         int left=0;
13         int right=num.length-1;
14         if(num[left]>num[right])//原序列是升序排列
15         {
16             while(left < right)
17             {
18                 int mid=(left+right)/2;
19                 if(num[mid]==num[left])
20                     left=mid+1;
21                 else if(num[mid]>num[left])
22                     left=mid;
23                 else 
24                     right=mid;
25                 
26             }
27         }
28         else //原序列是降序排列
29         {
30             while(left < right)
31             {
32                 int mid=(left+right)/2;
33                 if(num[mid]==num[left])
34                     right=mid-1;
35                 else if(num[mid]>=num[left])
36                     right=mid;
37                 else 
38                     left=mid;    
39             }
40         }
41         return num[left];
42     }
43     public static void main(String[] args)
44     {
45         int[] arr=new int[3];
46         arr[0]=3;
47         arr[1]=1;
48         arr[2]=2;
49         findMinInRotatedSortedArray a=new findMinInRotatedSortedArray();
50         System.out.println(a.findMin(arr));
51     }
52 }

 

posted @ 2014-11-16 22:47  evashi  阅读(199)  评论(0编辑  收藏  举报