代码之家  ›  专栏  ›  技术社区  ›  Srini Kandula

在带边界的整数数组中查找重复项

  •  3
  • Srini Kandula  · 技术社区  · 16 年前

    下面是我写的问题描述和算法。有什么需要改进的算法吗?

    给定一个大小未知的整数数组(仅包含0到30之间的数字),编写一个函数以返回包含所有重复项的整数数组。

    int[] findDupes(int[] array) {
        int[] found = new int[30];
        int[] dupes = new int[30];
        int dupesCount = 0;
        for (int i = 0; i < array.length; i++) {
            if (found[array[i]] <= 1) {
                found[array[i]]++;              
            }else{
                continue;
            }
            if(found[array[i]] > 1){
                dupes[dupesCount++] = array[i];
                if (dupesCount == 30)
                    break;
            }
        }
        if (dupesCount == 0)
            return new int[0];
        return dupes;
    }
    

    我假设运行此算法的最佳情况是n或30,以较低者为准 运行此算法的最坏情况是n,因为我必须扫描整个数组以查找重复项。有什么意见吗?

    4 回复  |  直到 16 年前
        1
  •  2
  •   deinst    16 年前

    你的想法是对的,但是问问你自己,这个街区到底是干什么的

        if(found[array[i]] > 1){
            dupes[dupesCount++] = array[i];
            if (dupesCount == 30)
                break;
        }
    

    什么时候点火?

    使用两个示例遍历代码,其中包括1000次出现0的数组。

    你到底要回来什么?为什么您需要特殊情况0。

    同时,最好的运行时间将大于30。在到达终点之前使它停止的最小输入是什么?

        2
  •  1
  •   illcar    16 年前

    需要更精确地定义问题。整数是否只有1或2次出现?是否可以出现0次或3次?

    如果一个整数只有1或2次出现,整数的范围是1到30;我将有一个位集,并在找到整数时翻转该位。当我读取完原始数组后,所有为0的位将表示包含重复项的整数。

        3
  •  0
  •   Ishtar    16 年前

    有点奇怪:

        if (found[array[i]] <= 1)              
        }else{
            continue;//happens if found[array[i]] > 1
        }
        if(found[array[i]] > 1){//usually don't get here, because of continue
    

    继续是只添加一次数字的修复程序吗?虽然它起作用,但代码是误导性的。

    如果只有一个重复项,是否必须返回30长度的数组?

    我建议通过拆分任务使代码变得更慢更好。

        4
  •  0
  •   Srini Kandula    16 年前

    这是嵌入了注释的修改版本。

    int[] found = new int[3];
        int[] dupes = new int[3];
        int dupesCount = 0;
        for (int i = 0; i < array.length; i++) {
            if (found[array[i]] <= 1) {
                found[array[i]]++;              
            }
            if(found[array[i]] > 1){ //duplicate found
                dupes[dupesCount++] = array[i];
    
                // if 30 duplicate are found don't scan the array any more
                // since the distinct numbers are only 30
                if (dupesCount == 30) 
                    break;
            }
        }
        if (dupesCount == 0)
            return null;
        return dupes;