主元素的概念是一个元素的出现次数占50%以上
快排方法,复杂度O(nlogn)
占50%,所以中间元素一定是主元素
int get(int A[], int n) {
sort(A,A+n);
return A[n/2];
}
利用主元素的特性求已知有主元素的数组的主元素,复杂度O(n)
因为其占50%以上,出现一次得++,不同得--,所以最后保留下来的一定是主元素
上代码,不懂的自己理解
int get(int A[], int n) {
int result, cnt;
result = A[0]; cnt = 1;
for(int i=1; i<n; i++) {
if(A[i] == result) {
cnt++;
}
else if(cnt == 1) {//相当于cnt--,因为cnt==0,result=A[i],cut=1
result = A[i];
cnt = 1;
} else {
cnt--;
}
}
return result;
}
利用主元素的特性求不知是否有主元素的数组的主元素,复杂度O(n)
在上个程序上进行加工,求出后判断其数量是否占总数50%,是就是主元素,否则无主元素
int get(int A[], int n) {
int result, cnt;
result = A[0]; cnt = 1;
for(int i=1; i<n; i++) {
if(A[i] == result) {
cnt++;
}
else if(cnt == 1) {
result = A[i];
cnt = 1;
} else {
cnt--;
}
}
cnt=0;
for(int i=0;i<n;i++){
if(A[i]==result)
cnt++;
}
if(cnt>(n/2))
return result;
else
return -1;
}