2017-07-05 25 views
-1
#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.請幫助!數組中的多數元素。它

+4

你知道你硬編碼'N = 6'? – Stargateur

+0

當沒有多數元素時,應該做什麼?假設它是按照你想要的方式寫的?你沒有包含處理這種情況的邏輯。 –

+0

正確的代碼版本會有複雜性 - 'O(n^2)'。檢查更多[有效的解決方案](http://www.geeksforgeeks.org/majority-element/) –

回答

-1
for (int j = 9; j < n; j++) { if (arr[j] == maj) count++; } 

這段代碼根本不會運行,因爲n是6,j是9,所以它不會進入循環。

您需要在進入循環時將j初始化爲低於n的值,以便根據您的要求繼續迭代。

+0

這不是一個答案。考慮在評論中寫下這些評論。 – iehrlich

+0

我編輯了我的答案,併成爲初學者,隨着時間的推移,我將正確地傳達答案。 –

0
#include <stdio.h> 
int main() { 
    int maj, count, n = 7; //n is size of arr 
    int arr[] = {1, 2, 2, 2, 2, 3, 4}; 
    int isFound = 0; //0 -> false, 1 -> true 

    for (int i = 0; i < n; i++) { 
     maj = arr[i]; 
     count = 1; //first elements is itself 
     isFound = 0; //by default we assume that no major elements is found 

     for (int j = i+1; j < n; j++) { //iterate from next elements onwards to right in array 
      if (arr[j] == maj) count++; 
     } 
     if (count > n/2) { 
      isFound = 1; 
      break; //major elements found; no need to iterator further; just break the loop now 
     } 
    } 
    if(isFound) printf("%d ", maj); 
    else printf("no major element"); 
    return 0; 
} 
+0

不需要使用'isFound',我們可以通過'i> = n'來檢查。如果(i> = n)'那麼沒有其他多數元素存在多數元素。 –

+0

@GAURANGVYAS是的,那是另一種方式:) – roottraveller

0

對於按照C標準函數main啓動不帶參數應聲明如下

int main(void) 

,儘量不要使用幻數。通常在你的程序中,它們是程序錯誤的原因。例如,您聲明數組arr有7個元素,但應保留數組中元素數的變量n使用值6進行初始化。另一個神奇的數字9在循環

for (int j = 9; j < n; j++) { 
      ^^^ 

使用有沒有必要寫外循環,Travers的整個陣列。當數組中不存在大多數數字時,程序也不會報告該情況。

使用你的方法有兩個循環的程序可以看看下面的方式

#include <stdio.h> 

int main(void) 
{ 
    int a[] = { 1, 2, 2, 2, 2, 3, 4 }; 
    const size_t N = sizeof(a)/sizeof(*a); 

    size_t i = 0; 
    for (; i < (N + 1)/2; i++) 
    { 
     size_t count = 1; 
     for (size_t j = i + 1; count < N/2 + 1 && j < N; j++) 
     { 
      if (a[i] == a[j]) ++count; 
     } 

     if (!(count < N/2 + 1)) break; 
    } 

    if (i != (N + 1)/2) 
    { 
     printf("The majority is %d\n", a[i]); 
    } 
    else 
    { 
     puts("There is no majority element"); 
    } 

    return 0; 
} 

其輸出

The majority is 2