C++演算法之 旋轉數組的最小數字,數組最小

來源:互聯網
上載者:User

C++演算法之 旋轉數組的最小數字,數組最小

題目:把一個數組最開始的若干個元素搬到數組的末尾,我們稱之為數組的旋轉。輸入一個遞增排序的數組的一個旋轉,輸出旋轉數組的最小元素。例如數組{3,4,5,1,2}為{1,2,3,4,5}的一個旋轉,該數組的最小值為1.

 

我們注意到旋轉之後的數組實際上可以劃分為兩個排序的子數組,而且前面的子數組的元素都大於或者等於後面子數組的元素。我們還可以注意到最小的元素剛好是這兩個子數組的分界線。我們試著用二元尋找法的思路在尋找這個最小的元素。

 

int MinInOrder(int array[], int i, int j){int result = array[i];for (int m = i+1; m <= j;m++){if (array[m] < result){result = array[m];}}return result;}int Min(int array[], int nlength){if (array == NULL || nlength < 0){throw new std::exception("Invalid parameters");}int index1   = 0;int index2   = nlength - 1;int indexMid = index1;while (array[index1] >= array[index2]){indexMid = index1+ (index2 - index1)/2;//indexMid = (index1+index2)/2;//如果三個數相等,那麼只能順序尋找if (array[index1] == array[index2] && array[index2] == array[indexMid]){return MinInOrder(array,index1,index2);}//如果中間的數字大於開頭的index1,那麼最小的數字一定在這個中間數的後面,令index1=mid這個中間數if(array[indexMid] >= array[index1]){index1 = indexMid;}//如果中間的數字小於結尾的index2,那麼最小的數字一定在這個中間數位前面,令index2=midelse if(array[indexMid] <= array[index2]){index2 = indexMid;}//當index1與index2相差為1 的時候,最小的數就是index2;if (index2 - index1 == 1){indexMid = index2;break;}}return array[indexMid];}


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.