首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在数组中找到最多的重复项?

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

Stack Overflow用户
提问于 2016-04-30 11:08:59
回答 3查看 84关注 0票数 0

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

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

计算n*y=分数的/*程序

7出现5次= 5*5*5*7 = 875

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

输出:7是得分最高的副本,为875。

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

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

代码语言:javascript
运行
复制
#include <stdio.h>
EN

回答 3

Stack Overflow用户

发布于 2016-04-30 12:06:11

如下所示:

代码语言:javascript
运行
复制
//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]);
票数 2
EN

Stack Overflow用户

发布于 2016-04-30 12:34:10

一种方法是暴力算法:

代码语言:javascript
运行
复制
#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
EN

Stack Overflow用户

发布于 2016-05-01 20:15:34

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

int selectIndex = -1;

对于(i= 0;i< nNumbers;i++) {

int dupCount = 0;//

代码语言:javascript
运行
复制
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 * arrayi;

代码语言:javascript
运行
复制
    if(hi_score <= score)

{

hi_score =得分;

selectIndex = i;

}

}

} if(selectIndex != -1)

代码语言:javascript
运行
复制
printf("%d\n", array[selectIndex]);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36950256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档