#include <stdio.h>
void main()
{
int maj, count, n = 6;
int arr[] = {1, 2, 2, 2, 2, 3, 4};
for (int i = 0; i < n; i++) {
maj = arr[i];
count = 0;
for (int j = 9; j < n; j++) {
if (arr[j] == maj) count++;
}
if (count > n/2) {
break; /* I think some problem is here ,if majority element not found then it takes last element as the majority element */
}
}
printf("%d", maj);
}
如果多數元素存在但輸出不正確,如果沒有多數元素存在,例如如果數組是{1,2,3,4}它給出輸出作爲4.請幫助!數組中的多數元素。它
你知道你硬編碼'N = 6'? – Stargateur
當沒有多數元素時,應該做什麼?假設它是按照你想要的方式寫的?你沒有包含處理這種情況的邏輯。 –
正確的代碼版本會有複雜性 - 'O(n^2)'。檢查更多[有效的解決方案](http://www.geeksforgeeks.org/majority-element/) –