【问题标题】:how can search this array [duplicate]如何搜索这个数组[重复]
【发布时间】:2014-02-05 18:56:33
【问题描述】:

给定 N 个整数,编写一个算法(以伪代码形式)计算具有 K 的差异。 输入 整数 N、差 K 和元素列表。 输出 一个整数,表示相差 K 的对数。

【问题讨论】:

    标签: algorithm pseudocode


    【解决方案1】:

    这样就可以了:

       START
       # Variables Initialization
       init Decision = 'continue';
       init N = 0;
       init integers_array = array();
    
       # Getting the list of Integers
        Do{
          prompt "Insert an Integer";
          input inserted_int;
          integers_array.push(inserted_int);
          prompt "Choose: Done or continue?!";
          input Decision;
        }while not (Decision == 'continue'); 
    
       # Getting the Searched Difference
        prompt "Insert the searched difference:";
        input K;
    
       # Preparing the search phase
        N = count(integers_array);
        init pairs_counter = 0;
    
        # Make a double loop on the same Integers array, and increment the counter when find          
          pairs, every pair will be counted twice!
        foreach (int i=0; i<N; i++){
           foreach (int j=0; j<N; j++){
               if (absolute(integers_array[i] - integers_array[j]) == K){
                  pairs_counter++;
               }
           }
        }
    
        # Divide by two to get the real number of Pairs
        true_pairs_counter = pairs_counter/2;
    
        output true_pairs_counter;
    
       END
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多