1. 程式人生 > >6、劍指offer--旋轉數組的最小數字

6、劍指offer--旋轉數組的最小數字

namespace 數字 log clu 有序 ios end esp offer

題目描述 把一個數組最開始的若幹個元素搬到數組的末尾,我們稱之為數組的旋轉。 輸入一個非遞減排序的數組的一個旋轉,輸出旋轉數組的最小元素。 例如數組{3,4,5,1,2}為{1,2,3,4,5}的一個旋轉,該數組的最小值為1。 NOTE:給出的所有元素都大於0,若數組大小為0,請返回0。 解題思路:本題中因為旋轉後的兩個子數組分別是有序的,因此不需要完全遍歷一遍得到結果,采用二分查找的方法解決;註意特殊情況左=中間=右,只能采用遍歷進行處理
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
4 //例如12345 的旋轉數組34512 這類的左側第一個值大一等於右側 由於每個子數組是排好序的,所以用二分查找logn 5 //例如01111 的旋轉數組11101 10111這種第一個值=中間值=最後值需要特殊處理 只能遍歷 n 6 class Solution { 7 public: 8 int minNumberInRotateArray(vector<int> rotateArray) { 9 int n = rotateArray.size(); 10 if(n==0) 11 return 0;
12 int index1 = 0; 13 int index2 = n-1; 14 int indexMid = index1; 15 while(rotateArray[index1]>=rotateArray[index2]) 16 { 17 if(index2-index1 == 1)//相差一個時,是查找截止條件 18 { 19 indexMid = index2; 20 break; 21 }
22 indexMid = (index1+index2)/2; 23 if(rotateArray[index1] == rotateArray[index2] && rotateArray[index1] == rotateArray[indexMid])//特殊處理 24 { 25 return MinInOrder(rotateArray,index1,index2); 26 } 27 if(rotateArray[indexMid]>=rotateArray[index1])//中間值大於左側值,最小值在右側 28 { 29 index1 = indexMid; 30 } 31 else if(rotateArray[indexMid] <=rotateArray[index2])//中間值小於右側值最小值在左側 32 { 33 index2 = indexMid; 34 } 35 } 36 return rotateArray[indexMid]; 37 38 } 39 int MinInOrder(vector<int> rotateArray,int index1,int index2) 40 { 41 int result = rotateArray[index1]; 42 for(int i=index1+1;i<=index2;i++) 43 { 44 if(rotateArray[i]<result) 45 { 46 result = rotateArray[i]; 47 } 48 } 49 return result; 50 } 51 }; 52 int main() 53 { 54 vector<int> a; 55 a.push_back(3); 56 a.push_back(4); 57 a.push_back(5); 58 a.push_back(1); 59 a.push_back(2); 60 Solution s; 61 int result = s.minNumberInRotateArray(a); 62 cout<<"the min of 12345 is"<<result<<endl; 63 64 vector<int> b; 65 b.push_back(1); 66 b.push_back(0); 67 b.push_back(1); 68 b.push_back(1); 69 b.push_back(1); 70 result = s.minNumberInRotateArray(b); 71 cout<<"the min of 01111 is"<<result<<endl; 72 return 0; 73 }

輸出結果截圖:
技術分享

6、劍指offer--旋轉數組的最小數字