2016-04-30 48 views
0

我不知道如何在數組中找到重複項。在找到重複數據後,如何找到數組中最重複的部分?

例如輸入:3 5 7 7 7 7 7 12 12 12 18 20

/*程序計算 N * N * N * Y =得分

7出現5次= 5 * 5 * 5 * 7 = 875

12出現3次= 3 * 3 * 3 * 12 = 324 */

輸出:7是在875

得分最高的重複我限制爲僅使用陣列,如果/否則,printf/scanf,循環..

到目前爲止我的代碼(僅適用於某些輸入):

#include <stdio.h> 
+2

'爲(I = 0 .. {對於(I = 1':使用變化的其他變量對於內部for循環 – BLUEPIXY

+0

你可以對數組進行排序,然後以一次通過的方式運行,保持最高級相遇的軌跡以及數字本身。 –

回答

2

這樣的:

//Provisional value 
int hi_score = INT_MIN;//#include <limits.h> 
int selectIndex = -1; 

for(i = 0; i < nNumbers; i++){ 
    int dupCount = 0; 
    if(selectIndex != -1 && array[selectIndex] == array[i]) 
     continue;//skip because It has already been calculated 

    for(j = 0; j < nNumbers; j++){//Examine all because unsorted 
     if((array[i] == array[j])) 
      ++dupCount; 
    } 
    if(dupCount > 1){// need ? 
     int score = dupCount * dupCount * dupCount * array[i]; 
     if(hi_score <= score){ 
      hi_score = score; 
      selectIndex = i; 
     } 
    } 
} 
if(selectIndex != -1) 
    printf("%d\n", array[selectIndex]); 
+1

你可以使用'for(j ='循環for'for(j = i ;'因爲你知道這個號碼以前沒有見過,所以你不需要t o重新掃描元素0..i-1 - 是嗎? –

+0

@JonathanLeffler但包括-10,-10,-10的情況:得分3 * 3 * 3 * -10 <2 * 2 * 2 * -10這是錯誤的分數。 – BLUEPIXY

+1

嗯...是的。你只跟蹤一個先前計算的值(具有當前最大值的那個值),而不是全部。在這種情況下,正如你所說,你需要重新掃描整個列表,以防萬一。 –

0

一種方法是窮舉算法:

#include <stdio.h> 
#include <limits.h> 

#define MAX_NUMBERS 15 

int calc_score(int number, int times) 
{ 
    return times*times*times*number; 
} 

int main(void) { 
    int a[MAX_NUMBERS] = { 3, 5, 7, 7, 7, 7, 7, 12, 12, 12, 18, 20,13,13,14 }; 

    int n; 
    int score; 
    int scoreMax = INT_MIN; 
    for (int i = 0; i < MAX_NUMBERS; i++) 
    { 
     int times = 0; 
     for (int j = 0; j < MAX_NUMBERS; j++) { if (a[i] == a[j])times++; } 
     score = calc_score(a[i], times); 
     if (score > scoreMax) { 
      scoreMax = score; 
      n = a[i]; 
     } 
    } 

    printf("%d is the highest scoring duplicate at %d\n", n, scoreMax); 
    //7 is the highest scoring duplicate at 875 
} 
0

//臨時值 int hi_score = INT_MIN; //#include

int selectIndex = -1;

爲(I = 0;我< nNumbers;我++){

INT dupCount = 0; //

if(selectIndex != -1 && array[selectIndex] == array[i]) 
    continue;//skip because It has already been calculated 

for(j = 0; j < nNumbers; j++){//Examine all because unsorted 
    if((array[i] == array[j])) 
     ++dupCount; 
} 

如果(dupCount> 1) {

//需要嗎?

int score = dupCount * dupCount * dupCount * array [i];

if(hi_score <= score) 

{

hi_score =得分;

selectIndex = i;

}

}

} 如果(selectIndex = -1!)

printf("%d\n", array[selectIndex]); 
相關問題