如何在数组中找到最多重复项?

时间:2016-04-30 03:08:59

标签: c arrays loops if-statement

我不知道如何在数组中找到重复项。找到重复后,

e.g。输入: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的得分最高的重复。

我只能使用数组,if / else,printf / scanf,loops ..

到目前为止我的代码(仅适用于某些输入):

String[] lines = str.split("(?<=\\))");

3 个答案:

答案 0 :(得分:2)

像这样:

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

答案 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
}

答案 2 :(得分:0)

//临时值 int hi_score = INT_MIN; // #include

int selectIndex = -1;

for(i = 0; i&lt; nNumbers; i ++) {

int dupCount = 0; //

unit UseLine_U;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Lines_U, StdCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    redOut: TRichEdit;
    Procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  line : TLine;

implementation

{$R *.dfm}

Procedure TForm1.FormCreate(Sender: TObject);
Var tempLine : string;
begin
   line := TLine.Create;
   line.Draw(tempLine);
   redOut.Lines.Add(tempLine);
end;
end.

if(dupCount&gt; 1) {

//需要吗?

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

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;
}

{

hi_score =得分;

selectIndex = i;

}

}

} if(selectIndex!= -1)

    if(hi_score <= score)
相关问题