博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【算法概论】分治算法:求主元素
阅读量:4176 次
发布时间:2019-05-26

本文共 1148 字,大约阅读时间需要 3 分钟。

时间复杂度:O(n*logn)

将数组A划分成两个数组A1和A2,各含有A中的一半元素。考虑以下的问题:如果知道了A1和A2中各自的主元素,是否会对找出A中的主元素有所帮助? → 分治法

/*找数组的主元素(主元素的重复次数超过数组大小的一半)。先将数组划分成两个数组A1和A2,找它们各自的主元素。*/#include 
#include
using namespace std;int Partition(int data[], int head, int tail);int main(){ int data[10] = { 5, 5, 3, 4, 4, 4, 4, 5, 5 }; int data[10] = { 5, 5, 5, 3, 4, 4, 5, 5, 4 }; if (Partition(data, 0, 9) != INT_MAX) { cout << Partition(data, 0, 9) << endl; } else { cout << "该数组没有主元素" << endl; } return 0;}int Partition(int data[], int head, int tail){ //划分到子数组只有一个元素,返回该元素 if (head == tail) { return data[head]; } int mid = (head + tail) / 2; int num1 = Partition(data, head, mid); int num2 = Partition(data, mid + 1, tail); if (num1 == num2) { //两个子数组的主元素不存在,则原数组也不存在主元素 //两个子数组的主元素存在相等,则原数组的主元素一定为子数组的主元素 return num1; } else { //子数组的主元素都存在但不相等,检查它们在原数组中是否是主元素 int cnt1 = 0, cnt2 = 0; for (int i = head; i <= tail; ++i) { if (data[i] == num1) { ++cnt1; } if (data[i] == num2) { ++cnt2; } } if (cnt1 > (tail - head + 1) / 2) { return num1; } else if (cnt2 > (tail - head + 1) / 2) { return num2; } else { return INT_MAX; } }}

 

转载地址:http://bttai.baihongyu.com/

你可能感兴趣的文章
Tomcat6数据源配置
查看>>
xmove.pl
查看>>
Excel简单五子棋
查看>>
Java之synchronized小例
查看>>
jstl之set与out小例
查看>>
apploc.bat
查看>>
乱撞解决word只能以安全模式启动
查看>>
Oracle外部表小例
查看>>
在VS.NET的VC++中运行控制台程序后暂停
查看>>
Linux下rz,sz与ssh,SecureCRT的配合使用
查看>>
一个使用Pro*C实现增删改查的小例子
查看>>
Save could not be completed. Eclipse国际化的问题解决
查看>>
Xblo(JSP+Servlet+JavaBean+Oracle单用户Blog)
查看>>
Unable to use IEC module under PortablePython_1.1_py2.5.4
查看>>
实用英文地址书写格式
查看>>
在oracle中通过connect by prior来实现递归查询!
查看>>
百度空间如何才能另存为 mht
查看>>
How to Reset or Change Microsoft Office 2007 Product License Key or Volume License Key (VLK)
查看>>
使用java concurrent调用xmlp api生成pdf
查看>>
Oracle日期计算之INTERVAL
查看>>