首页 > 其他 > 详细

编程之美--2.10

时间:2014-06-26 17:13:56      阅读:339      评论:0      收藏:0      [点我收藏+]

题目描述:求数组的最大值和最小值,并且计算比较次数

思路:

(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 }

 

编程之美--2.10,布布扣,bubuko.com

编程之美--2.10

原文:http://www.cnblogs.com/cane/p/3808762.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!