标签: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 res 10 { 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 }
标签:style class blog code color os
原文地址:http://www.cnblogs.com/cane/p/3808762.html