算法找出重复的数字数组中的---用最快的方法 [英] Algorithm to find the duplicate numbers in an array ---Fastest Way

查看:622
本文介绍了算法找出重复的数字数组中的---用最快的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要最快和简单的算法查找重复的数字在一个阵列,还应该能知道重复数

I need the fastest and simple algorithm which finds the duplicate numbers in an array, also should be able to know the number of duplicates.

例如:如果数组 {2,3,4,5,2,4,6,2,4,7,3,8,2}

我应该能知道,有4个2的,两个3的和三个4的

I should be able to know that there are four 2's, two 3's and three 4's.

推荐答案

这里的,做它与标准输入C版本;它以最快的速度输入的长度(注意,参数的命令行上的数量是有限的......),但应该给你如何进行一个想法:

here's a C version that does it with standard input; it's as fast as the length of the input (beware, the number of parameters on the command line is limited...) but should give you an idea on how to proceed:

#include <stdio.h>

int main ( int argc, char **argv ) {
    int dups[10] = { 0 };
    int i;

    for ( i = 1 ; i < argc ; i++ ) 
    	dups[atoi(argv[i])]++;

    for ( i = 0 ; i < 10 ; i++ )
    	printf("%d: %d\n", i, dups[i]);

    return 0;
}

例如用法:

    $ gcc -o dups dups.c

    $ ./dups 0 0 3 4 5
0: 2
1: 0
2: 0
3: 1
4: 1
5: 1
6: 0
7: 0
8: 0
9: 0

警告:

  • 如果您打算也算10S,11S的数量,等等 - >复本[]数组必须做大

  • if you plan to count also the number of 10s, 11s, and so on -> the dups[] array must be bigger

作为一个练习是实现从一个整数数组读取并确定自己的位置

left as an exercise is to implement reading from an array of integers and to determine their position

这篇关于算法找出重复的数字数组中的---用最快的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆