【问题标题】:pseudo code to find the numbers which appear more than once in a list [closed]用于查找列表中多次出现的数字的伪代码[关闭]
【发布时间】:2012-01-18 17:44:26
【问题描述】:

我有一个像1,2,199,100,8,100,199,1001,5,9 这样的系列,我必须编写一个伪代码来找出在上面的列表中出现多次的数字。我可以清楚地看到 199 和 100 在列表中出现了两次,这应该是答案,但我应该如何为其编写伪代码? 我的逻辑是这样的:

   array x = {1,2,199,100,8,100,199,1001,5,9}
   array y
   array j
for(int i = 0;i< 9; i++){
 if x[i] exists in y
     j[i] = y
 else
    y[i] = x


}

【问题讨论】:

  • @TomasNarros 我尝试过的问题存在于问题中..想不到更多。

标签: java algorithm pseudocode series


【解决方案1】:

使用快速排序或合并排序(n log n)对列表进行排序,然后对列表进行一次遍历,将当前数字与前一个 O(n) 进行比较。如果前一个数字等于当前数字,则您有一个重复。

编辑:

Array array = {1,2,199,100,8,100,199,1001,5,9}
Array sorted = sort(array)
for (int i=1; i<sorted.length; i++)
    int p = sorted[i-1]
    int c = sorted[i]
    if (p==c) print "duplicate"

【讨论】:

  • 你能写一个sn-p的伪代码吗?
【解决方案2】:

通过exists() 检查,这看起来与冒泡排序具有相同的性能。如果您对数组进行排序(使用更快的排序)然后再进行一次额外的传递来识别骗子,它可能会更快。 如果我正确理解您的伪代码,它似乎有一个错误。不应该更像:

for(int i = 0;i< 9; i++){
 if x[i] exists in y
     j.push(x[i]);
 else
    y.push(x[i]);    

}

【讨论】:

  • 是的,你是对的!应该是这样的。
【解决方案3】:
// loop through list of numbers
    // count apperences in list
    // if appearences > 1
            // remove all instances, add to results list

// print the results list -- this will have all numbers that appear more than once.

【讨论】:

  • 第二行呢?如何计算出场次数?
  • 无论您使用哪种语言,最有可能都有这样做的方法。类似的事情我不会在伪代码中详细介绍。
【解决方案4】:

假设您仅限于使用原始类型而不是能够使用java.util.Collections,您可以这样工作:

For each value in `x`
  Grab that value
  If the list of duplicates does not contain that value
    See if that value reoccurs at a later index in `x`
      If it does, add it to the list of duplicates

这是翻译成 Java 的伪代码:

private void example() {
    int [] x = new int [] {1,2,199,100,8,100,199,1001,5,9, 199};
    int [] duplicates = new int[x.length];

    for (int i = 0; i < x.length; i++) {
      int key = x[i];
      if (!contains(duplicates, key)) {
        // then check if this number is a duplicate
        for (int j = i+1; j < x.length-1; j++) {
          // start at index i+1 (no sense checking same index as i, or before i, since those are alreayd checked
          // and stop at x.length-1 since we don't want an array out of bounds exception
          if (x[j] == key) {
            // then we have a duplicate, add to the list of duplicates
            duplicates[i] = key;
          }
        }
      }
    }

    for (int n = 0; n < duplicates.length; n++) {
      if (duplicates[n] != 0) {
        System.out.println(duplicates[n]);
      }
    }
}

  private boolean contains(int [] array, int key) {
    for (int i = 0; i < array.length; i++) {
      if (array[i] == key) {
        return true;
      }
    }
    return false;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2020-03-27
    • 1970-01-01
    • 2014-10-28
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多