編程之美--2.10

來源:互聯網
上載者:User

標籤:style   class   blog   code   color   os   

題目描述:求數組的最大值和最小值,並且計算比較次數

思路:

(1)普通思路是遍曆一遍,得比較2*N次

(2)分治,具體計算可以參考書上內容,演算法時間複雜度是O(logn)

 1 #include <iostream> 2 #include <queue> 3 #include <climits> 4 #include <algorithm> 5 #include <memory.h> 6 #include <stdio.h> 7 using namespace std; 8  9 struct res10 {11     int mx;12     int ml;13 };14 15 res fun(vector<int> a,int s,int e)16 {17     res ans;18     if(s == e)19     {20         ans.ml = a[s];21         ans.mx = a[s];22         return ans;23     }24     int m = (s+e)>>1;25     res ans1 = fun(a,s,m);26     res ans2 = fun(a,m+1,e);27     ans.ml = min(ans1.ml,ans2.ml);28     ans.mx = max(ans1.mx,ans2.mx);29     return ans;30 }31 32 int main()33 {34     vector<int> a;35     a.push_back(1);36     a.push_back(2);37     a.push_back(3);38     res tmp = fun(a,0,2);39     cout<<tmp.ml<<endl;40     cout<<tmp.mx<<endl;41     return 0;42 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.