【问题标题】:java codility Max-Countersjava codility Max-Counters
【发布时间】:2013-10-28 06:13:49
【问题描述】:

我一直在尝试解决以下任务:

给你 N 个计数器,初始设置为 0,你有两种可能的操作:

    increase(X) − counter X is increased by 1,
    max_counter − all counters are set to the maximum value of any counter.

给出了一个由 M 个整数组成的非空零索引数组 A。这个数组代表连续的操作:

    if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
    if A[K] = N + 1 then operation K is max_counter.

例如,给定整数 N = 5 和数组 A,这样:

A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

每次连续操作后计数器的值将是:

(0, 0, 1, 0, 0)
(0, 0, 1, 1, 0)
(0, 0, 1, 2, 0)
(2, 2, 2, 2, 2)
(3, 2, 2, 2, 2)
(3, 2, 2, 3, 2)
(3, 2, 2, 4, 2)

目标是计算所有操作后每个计数器的值。

struct Results {
  int * C;
  int L;
}; 

写一个函数:

struct Results solution(int N, int A[], int M); 

给定一个整数 N 和一个由 M 个整数组成的非空零索引数组 A,返回一个表示计数器值的整数序列。

序列应返回为:

    a structure Results (in C), or
    a vector of integers (in C++), or
    a record Results (in Pascal), or
    an array of integers (in any other programming language).

例如,给定:

A[0] = 3
A[1] = 4
A[2] = 4
A[3] = 6
A[4] = 1
A[5] = 4
A[6] = 4

该函数应返回 [3, 2, 2, 4, 2],如上所述。

假设:

    N and M are integers within the range [1..100,000];
    each element of array A is an integer within the range [1..N + 1].

复杂性:

    expected worst-case time complexity is O(N+M);
    expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

输入数组的元素可以修改。

这是我的解决方案:

import java.util.Arrays;

class Solution {
    public int[] solution(int N, int[] A) {

        final int condition = N + 1;
        int currentMax = 0;
        int countersArray[] = new int[N];

        for (int iii = 0; iii < A.length; iii++) {
            int currentValue = A[iii];
            if (currentValue == condition) {
                Arrays.fill(countersArray, currentMax);
            } else {
                int position = currentValue - 1;
                int localValue = countersArray[position] + 1;
                countersArray[position] = localValue;

                if (localValue > currentMax) {
                    currentMax = localValue;
                }
            }

        }

        return countersArray;
    }
}

这是代码评估: https://codility.com/demo/results/demo6AKE5C-EJQ/

你能告诉我这个解决方案有什么问题吗?

【问题讨论】:

    标签: java arrays algorithm


    【解决方案1】:

    问题出在这段代码上:

    for (int iii = 0; iii < A.length; iii++) {
         ...
         if (currentValue == condition) {
             Arrays.fill(countersArray, currentMax);
         }
         ...
    }
    

    假设数组A 的每个元素都使用值N+1 进行了初始化。由于函数调用Arrays.fill(countersArray, currentMax) 的时间复杂度为O(N),那么总体而言,您的算法的时间复杂度为O(M * N)。我认为解决此问题的方法不是在调用max_counter 操作时显式更新整个数组A,而是可以将上次更新的值保留为变量。当调用第一个操作(增量)时,您只需查看您尝试增加的值是否大于last_update。如果是,您只需将值更新为 1,否则将其初始化为 last_update + 1。当调用第二个操作时,您只需将last_update 更新为current_max。最后,当您完成并尝试返回最终值时,您再次将每个值与last_update 进行比较。如果它更大,则保留该值,否则返回last_update

    class Solution {
        public int[] solution(int N, int[] A) {
    
            final int condition = N + 1;
            int currentMax = 0;
            int lastUpdate = 0;
            int countersArray[] = new int[N];
    
            for (int iii = 0; iii < A.length; iii++) {
                int currentValue = A[iii];
                if (currentValue == condition) {
                    lastUpdate = currentMax
                } else {
                    int position = currentValue - 1;
                    if (countersArray[position] < lastUpdate)
                        countersArray[position] = lastUpdate + 1;
                    else
                        countersArray[position]++;
    
                    if (countersArray[position] > currentMax) {
                        currentMax = countersArray[position];
                    }
                }
    
            }
    
            for (int iii = 0; iii < N; iii++) {
               if (countersArray[iii] < lastUpdate)
                   countersArray[iii] = lastUpdate;
            }
    
            return countersArray;
        }
    }
    

    【讨论】:

    • 理论上这听起来是对的,但我还没有尝试过,看看是否能给 100 分
    • 这是假设输入的每个数组都比N小1,可能不是这样?
    • 此解决方案 100% 有效。作为我和其他人的助手,您能否详细说明if (countersArray[position] &lt; lastUpdate) countersArray[position] = lastUpdate + 1; 的逻辑,即用英文术语,为什么您将值设置为lastUpdate + 1,而不是lastUpdate?谢谢
    • @mils ,假设我们只将position 索引处的计数器设置为lastUpdate。在这种情况下,我们只应用max_counter 操作,而实际上我们已经看到了至少两个操作:max_counterincrease(position + 1)。如果不是后者,我们甚至不会更改此计数器的值,直到 @sve 解决方案中的第二个(也是最后一个)for 循环。
    • 不错的解决方案。我应用你的方法让我的方法达到 100%。我的收获是比较值(有很多 操作)比赋值便宜。每次更新所有计数器的成本太高。答案是跟踪当前最大值和最后一次“扫描”,此时一切都设置为最大值。
    【解决方案2】:

    问题在于,当您获得大量 max_counter 操作时,您会收到大量对 Arrays.fill 的调用,这会使您的解决方案变慢。

    您应该保留currentMaxcurrentMin

    • 当您获得max_counter 时,您只需设置currentMin = currentMax
    • 如果你得到另一个值,我们称之为i
      • 如果位置i - 1 的值小于或等于currentMin,则将其设置为currentMin + 1
      • 否则,您将增加它。

    最后只需再次遍历计数器数组并将小于currentMin 的所有内容设置为currentMin

    【讨论】:

      【解决方案3】:

      我开发的另一个可能值得考虑的解决方案:http://codility.com/demo/results/demoM658NU-DYR/

      【讨论】:

      • @moda,你介意解释一下你的代码吗?我似乎不明白它是如何完成 maxcounter 任务的。虽然我理解代码,但这种方法非常好,以至于我从来没有想过用这种方式解决它。那么,如果您能解释一下您为什么采用这种方法?
      • “另一个”怎么样? @helpdesk ,考虑阅读上面的@sve 的解决方案。这里B 变量等同于lastUpdate 变量。
      • 这是一个很棒的答案。我将它转换为 swift 4,它又好又干净。实际上,我很惊讶它是多么容易。这节课的说明绝对糟糕。
      【解决方案4】:

      这是这个问题的 100% 解决方案。

      // you can also use imports, for example:
      // import java.math.*;
      class Solution {
          public int[] solution(int N, int[] A) {
              int counter[] = new int[N];
              int n = A.length;
              int max=-1,current_min=0;
      
              for(int i=0;i<n;i++){
                  if(A[i]>=1 && A[i]<= N){
                      if(counter[A[i] - 1] < current_min) counter[A[i] - 1] = current_min;
                      counter[A[i] - 1] = counter[A[i] - 1] + 1;
                      if(counter[A[i] - 1] > max) max = counter[A[i] - 1];
                  }
                  else if(A[i] == N+1){
                      current_min = max;
                  }
              }
              for(int i=0;i<N;i++){
                  if(counter[i] < current_min) counter[i] =  current_min;
              }
              return counter;
          }
      }
      

      【讨论】:

        【解决方案5】:

        我正在添加另一个 Java 100 解决方案,其中包含一些测试用例,它们很有帮助。

        // https://codility.com/demo/results/demoD8J6M5-K3T/ 77
        // https://codility.com/demo/results/demoSEJHZS-ZPR/ 100
        public class MaxCounters {
        
          // Some testcases
          // (1,[1,2,3]) = [1]
          // (1,[1]) = [1]
          // (1,[5]) = [0]
          // (1,[1,1,1,2,3]) = 3
          // (2,[1,1,1,2,3,1]) = [4,3]
          // (5, [3, 4, 4, 5, 1, 4, 4]) = (1, 0, 1, 4, 1)
          public int[] solution(int N, int[] A) {
              int length = A.length, maxOfCounter = 0, lastUpdate = 0;
              int applyMax = N + 1;
              int result[] = new int[N];
        
              for (int i = 0; i < length; ++i ) {
                  if(A[i] == applyMax){
                      lastUpdate = maxOfCounter;
                  } else if (A[i] <= N)  {
                      int position = A[i]-1;
                      result[position] = result[position] > lastUpdate
                                                ? result[position] + 1 : lastUpdate + 1;
                      // updating the max for future use
                      if(maxOfCounter <=  result[position]) {
                          maxOfCounter = result[position];
                      }
                  }
             }
             // updating all the values that are less than the lastUpdate to the max value
             for (int i = 0; i < N; ++i) {
                 if(result[i] < lastUpdate) {
                     result[i] = lastUpdate;
                 }
             }
             return result;
           }
        }
        

        【讨论】:

          【解决方案6】:

          这是我的 C++ 解决方案,它在代码性上得到了 100。这个概念和上面解释的一样。

          int maxx=0;
          int lastvalue=0;
          void set(vector<int>& A, int N,int X)
              {
                  for ( int i=0;i<N;i++)
                      if(A[i]<lastvalue)
                          A[i]=lastvalue;
              }
          
          vector<int> solution(int N, vector<int> &A) {
              // write your code in C++11
          
              vector<int> B(N,0);
              for(unsigned int i=0;i<A.size();i++)
                  {
                      if(A[i]==N+1)
                         lastvalue=maxx;
          
                      else
                      {   if(B[A[i]-1]<lastvalue)
                              B[A[i]-1]=lastvalue+1;
                          else
                              B[A[i]-1]++;
                          if(B[A[i]-1]>maxx)
                              maxx=B[A[i]-1];
                      }
          
                  }
                  set(B,N,maxx);
              return B;
          }
          

          【讨论】:

            【解决方案7】:
            vector<int> solution(int N, vector<int> &A)
            {
                std::vector<int> counters(N);
                auto max = 0;
                auto current = 0;
            
                for (auto& counter : A)
                {
                    if (counter >= 1 && counter <= N)
                    {
                        if (counters[counter-1] < max)
                            counters[counter - 1] = max;
            
                        counters[counter - 1] += 1;
            
                        if (counters[counter - 1] > current)
                            current = counters[counter - 1];
                    }
                    else if (counter > N)
                        max = current;
            
                }
            
                for (auto&& counter : counters)
                    if (counter < max)
                        counter = max;
            
                return counters;
            }
            

            【讨论】:

              【解决方案8】:

              我的 java 解决方案,带有详细解释 100% 正确性,100% 性能:

              时间复杂度O(N+M)

               public static int[] solution(int N, int[] A) {
              
                  int[] counters = new int[N];
                  //The Max value between all counters at a given time
                  int max = 0;
              
                  //The base Max that all counter should have after the "max counter" operation happens
                  int baseMax = 0;
              
                  for (int i = 0; i < A.length; i++) {
              
                      //max counter Operation ==> updating the baseMax
                      if (A[i] > N) {
                          // Set The Base Max that all counters should have
                          baseMax = max;
              
                      }
              
                      //Verify if the value is bigger than the last baseMax because at any time a "max counter" operation can happen and the counter should have the max value
                      if (A[i] <= N && counters[A[i] - 1] < baseMax) {
                          counters[A[i] - 1] = baseMax;
                      }
              
                      //increase(X) Operation => increase the counter value
                      if (A[i] <= N) {
                          counters[A[i] - 1] = counters[A[i] - 1] + 1;
              
                          //Update the max
                          max = Math.max(counters[A[i] - 1], max);
                      }
                  }
              
                  //Set The remaining values to the baseMax as not all counters are guaranteed to be affected by an increase(X) operation in "counters[A[i] - 1] = baseMax;"
                  for (int j = 0; j < N; j++) {
                      if (counters[j] < baseMax)
                          counters[j] = baseMax;
                  }
              
                  return counters;
              }
              

              【讨论】:

                【解决方案9】:
                  vector<int> solution(int N, vector<int> &A) 
                {
                    std::vector<int> counter(N, 0); 
                    int max = 0;
                    int floor = 0;
                
                    for(std::vector<int>::iterator i = A.begin();i != A.end(); i++)
                    {
                        int index = *i-1;
                        if(*i<=N && *i >= 1)
                        {
                            if(counter[index] < floor)
                              counter[index] = floor;
                            counter[index] += 1;
                            max = std::max(counter[index], max);
                        }
                        else
                        {
                            floor = std::max(max, floor);
                        }
                    }
                    for(std::vector<int>::iterator i = counter.begin();i != counter.end(); i++)
                    {
                       if(*i < floor)
                         *i = floor;
                    }
                    return counter;
                }
                

                【讨论】:

                  【解决方案10】:

                  Hera 是我的 AC Java 解决方案。这个想法和@Inwvr解释的一样:

                  public int[] solution(int N, int[] A) {
                          int[] count = new int[N];
                          int max = 0;
                          int lastUpdate = 0;
                          for(int i = 0; i < A.length; i++){
                              if(A[i] <= N){
                                  if(count[A[i]-1] < lastUpdate){
                                      count[A[i]-1] = lastUpdate+1;   
                                  }
                                  else{
                                      count[A[i]-1]++;
                                  }    
                                  max = Math.max(max, count[A[i]-1]);
                              }
                              else{
                                  lastUpdate = max;   
                              }
                          }  
                          for(int i = 0; i < N; i++){
                              if(count[i] < lastUpdate)
                                  count[i] = lastUpdate;
                          }    
                          return count;
                      }
                  

                  【讨论】:

                    【解决方案11】:

                    在上面的帮助下,我在 PHP 中获得了 100 分

                    function solution($N, $A) {
                        $B = array(0);
                        $max = 0;
                    
                        foreach($A as $key => $a) {
                            $a -= 1;
                            if($a == $N) {
                                $max = max($B);
                            } else {
                                if(!isset($B[$a])) {
                                    $B[$a] = 0;
                                }
                    
                                if($B[$a] < $max) {
                                    $B[$a] = $max + 1;
                                } else {
                                    $B[$a] ++;
                                }
                    
                            }
                    
                        }
                    
                        for($i=0; $i<$N; $i++) {
                            if(!isset($B[$i]) || $B[$i] < $max) {
                                $B[$i] = $max;
                            }
                    
                        }
                    
                        return $B;
                    
                    
                    }
                    

                    【讨论】:

                      【解决方案12】:

                      这是该问题的另一种 C++ 解决方案。

                      理由总是一样的。

                      1. 避免在指令 2 时将所有计数器设置为最大计数器,因为这会将复杂度提高到 O(N*M)。
                      2. 等到我们在单个计数器上获得另一个操作代码。
                      3. 此时算法会记住它是否遇到了 max_counter 并因此设置计数器值。

                      代码如下:

                      vector<int> MaxCounters(int N, vector<int> &A) 
                      {
                          vector<int> n(N, 0);
                          int globalMax = 0;
                          int localMax = 0;
                      
                          for( vector<int>::const_iterator it = A.begin(); it != A.end(); ++it)
                          {
                              if ( *it >= 1 && *it <= N)
                              {
                                  // this is an increase op.
                                  int value = *it - 1;
                                  n[value] = std::max(n[value], localMax ) + 1;
                                  globalMax = std::max(n[value], globalMax);
                              }
                              else
                              {
                                  // set max counter op.
                                  localMax = globalMax;
                              }
                          }
                      
                          for( vector<int>::iterator it = n.begin(); it != n.end(); ++it)
                              *it = std::max( *it, localMax );
                      
                          return n;
                      }
                      

                      【讨论】:

                        【解决方案13】:

                        100%,O(m+n)

                        public int[] solution(int N, int[] A) {
                        
                            int[] counters = new int[N];
                            int maxAIs = 0;
                            int minAShouldBe = 0;
                        
                            for(int x : A) {
                                if(x >= 1 && x <= N) {
                                    if(counters[x-1] < minAShouldBe) {
                                        counters[x-1] = minAShouldBe;
                                    }
                        
                                    counters[x-1]++;
                        
                                    if(counters[x-1] > maxAIs) {
                                        maxAIs = counters[x-1];
                                    }
                                } else if(x == N+1) {
                                    minAShouldBe = maxAIs;
                                }
                            }
                        
                            for(int i = 0; i < N; i++) {
                                if(counters[i] < minAShouldBe) {
                                    counters[i] = minAShouldBe;
                                }
                            }
                        
                            return counters;
                        }
                        

                        【讨论】:

                          【解决方案14】:

                          这是我的代码,但它的 88% 原因是 10000 个元素需要 3.80 秒而不是 2.20 秒

                          类解决方案{

                          boolean maxCalled;
                          
                          public int[] solution(int N, int[] A) {
                          
                          int max =0;
                          int [] counters = new int [N];
                              int temp=0;
                              int currentVal = 0;
                              for(int i=0;i<A.length;i++){
                              currentVal = A[i];
                              if(currentVal <=N){
                                  temp = increas(counters,currentVal);
                                  if(temp > max){
                                  max = temp;
                                  }
                              }else{
                                  if(!maxCalled)
                                  maxCounter(counters,max);
                              }
                          
                              }
                          
                              return counters;
                          
                          }
                          
                          
                          int increas (int [] A, int x){  
                           maxCalled = false;
                           return ++A[x-1];  
                           //return t;
                          }
                          
                          void maxCounter (int [] A, int x){
                           maxCalled = true;
                            for (int i = 0; i < A.length; i++) {
                           A[i] = x;
                            }
                          
                          }
                          

                          }

                          【讨论】:

                            【解决方案15】:

                            Arrays.fill() 在数组交互中调用使程序 O(N^2)

                            Here 是一个可能的解决方案,它的运行时间为 O(M+N)。

                            想法是——

                            1. 对于第二个操作,跟踪通过增量获得的最大值,这是我们在当前迭代之前的基础值,任何值都不能小于这个。

                            2. 对于第一次操作,如果需要,在增量之前将值重置为基值。

                              public static int[] 解决方案(int N, int[] A) { int counters[] = new int[N];

                              int base = 0;
                              int cMax = 0;
                              
                              for (int a : A) {
                                  if (a > counters.length) {
                                      base = cMax;
                                  } else {
                                      if (counters[a - 1] < base) {
                                          counters[a - 1] = base;
                                      }
                              
                                      counters[a - 1]++;
                              
                                      cMax = Math.max(cMax, counters[a - 1]);
                                  }
                              }
                              
                              for (int i = 0; i < counters.length; i++) {
                                  if (counters[i] < base) {
                                      counters[i] = base;
                                  }
                              }
                              
                              return counters;
                              

                              }

                            【讨论】:

                              【解决方案16】:

                              按照我在 JAVA (100/100) 中的解决方案。

                              public boolean isToSum(int value, int N) {
                                  return value >= 1 && value <= N;
                              }
                              
                              public int[] solution(int N, int[] A) {
                                  int[] res = new int[N];
                                  int max =0;
                                  int minValue = 0;
                              
                                  for (int i=0; i < A.length; i++){
                                      int value = A[i];
                                      int pos = value -1;
                                      if ( isToSum(value, N)) {
                                          if( res[pos] < minValue) {
                                              res[pos] = minValue;
                                          }
                                          res[pos] += 1;
                                          if (max < res[pos]) {
                                              max = res[pos];
                                          }
                                      } else {
                                          minValue = max;
                                      }
                                  }
                              
                                  for (int i=0; i < res.length; i++){
                                      if ( res[i] < minValue ){
                                          res[i] = minValue;
                                      }
                                  }
                                  return res;
                              }
                              

                              【讨论】:

                                【解决方案17】:

                                我的解决方案是:

                                public class Solution {  
                                
                                        public int[] solution(int N, int[] A) {
                                
                                            int[] counters = new int[N];
                                            int[] countersLastMaxIndexes = new int[N];
                                            int maxValue = 0;
                                            int fixedMaxValue = 0;
                                            int maxIndex = 0;
                                            for (int i = 0; i < A.length; i++) {
                                                if (A[i] <= N) {
                                                    if (countersLastMaxIndexes[A[i] - 1] != maxIndex) {
                                                        counters[A[i] - 1] = fixedMaxValue;
                                                        countersLastMaxIndexes[A[i] - 1] = maxIndex;
                                
                                                    }
                                                    counters[A[i] - 1]++;
                                                    if (counters[A[i] - 1] > maxValue) {
                                                        maxValue = counters[A[i] - 1];
                                                    }
                                                } else {
                                                    maxIndex = i;
                                                    fixedMaxValue = maxValue;
                                                }
                                
                                            }
                                            for (int i = 0; i < countersLastMaxIndexes.length; i++) {
                                                if (countersLastMaxIndexes[i] != maxIndex) {
                                                    counters[i] = fixedMaxValue;
                                                    countersLastMaxIndexes[i] = maxIndex;
                                                }
                                            }
                                
                                            return counters;
                                        }
                                }
                                

                                【讨论】:

                                  【解决方案18】:

                                  在我的 Java 解决方案中,我仅在需要时更新了解决方案 [] 中的值。最后用正确的值更新了解决方案[]。

                                  public int[] solution(int N, int[] A) {
                                      int[] solution = new int[N];
                                      int maxCounter = 0;
                                      int maxCountersSum = 0;
                                      for(int a: A) {
                                          if(a >= 1 && a <= N) {
                                              if(solution[a - 1] < maxCountersSum)
                                                  solution[a - 1] = maxCountersSum;
                                              solution[a - 1]++;
                                              if(solution[a - 1] > maxCounter)
                                                  maxCounter = solution[a - 1];
                                          }
                                          if(a == N + 1) {
                                              maxCountersSum = maxCounter;
                                          }
                                      }
                                      for(int i = 0; i < N; i++) {
                                          if(solution[i] < maxCountersSum)
                                              solution[i] = maxCountersSum;
                                      }
                                  
                                      return solution;
                                  }
                                  

                                  【讨论】:

                                    【解决方案19】:

                                    这是我的 python 解决方案:

                                    def solution(N, A):
                                        # write your code in Python 3.6
                                        RESP = [0] * N
                                        MAX_OPERATION = N + 1
                                        current_max = 0
                                        current_min = 0
                                        for operation in A:
                                            if operation != MAX_OPERATION:
                                                if RESP[operation-1] <= current_min:
                                                    RESP[operation-1] = current_min + 1
                                                else:
                                                    RESP[operation-1] += 1
                                    
                                                if RESP[operation-1] > current_max:
                                                    current_max = RESP[operation-1]
                                            else:
                                                if current_min == current_max:
                                                    current_min += 1
                                                else:
                                                    current_min = current_max
                                    
                                        for i, val in enumerate(RESP):
                                            if val < current_min:
                                                RESP[i] = current_min
                                        return RESP
                                    

                                    【讨论】:

                                      【解决方案20】:
                                      def sample_method(A,N=5):
                                          initial_array = [0,0,0,0,0]
                                      for i in A:
                                      
                                          if(i>=1):
                                            if(i<=N):
                                              initial_array[i-1]+=1
                                            else:
                                              for a in range(len(initial_array)):
                                                initial_array[a]+=1
                                          print i
                                          print initial_array
                                      

                                      【讨论】:

                                      • 尝试对您的解决方案进行小幅评价
                                      • 对您的解决方案进行简短说明会有所帮助。
                                      【解决方案21】:

                                      这是我使用 python 3.6 的解决方案。结果是 100% 的正确性,但 40% 的性能(其中大部分是因为超时)。仍然无法弄清楚如何优化此代码,但希望有人能发现它有用。

                                      def solution(N, A):
                                          count = [0]*(N+1)
                                          for i in range(0,len(A)):
                                              if A[i] >=1 and A[i] <= N:
                                                  count[A[i]] += 1
                                              elif A[i] == (N+1): 
                                                  count = [max(count)] * len(count)
                                          count.pop(0)
                                          return count
                                      

                                      【讨论】:

                                        【解决方案22】:

                                        打字稿:

                                        function counters(numCounters: number, operations: number[]) {
                                        const counters = Array(numCounters)
                                        
                                        let max = 0
                                        let currentMin = 0
                                        
                                        for (const operation of operations) {
                                            if (operation === numCounters + 1) {
                                                currentMin = max
                                            } else {
                                                if (!counters[operation - 1] || counters[operation - 1] < currentMin) {
                                                    counters[operation - 1] = currentMin
                                                }
                                        
                                                counters[operation - 1] = counters[operation - 1] + 1
                                        
                                                if (counters[operation - 1] > max) {
                                                    max += 1
                                                }
                                            }
                                        }
                                        
                                        for (let i = 0; i < numCounters; i++) {
                                            if (!counters[i] || counters[i] < currentMin) {
                                                counters[i] = currentMin
                                            }
                                        }
                                        
                                        return counters
                                        

                                        }

                                        console.log(solution=${counters(5, [3, 4, 4, 6, 1, 4, 4])})

                                        【讨论】:

                                          【解决方案23】:

                                          100 分 JavaScript 解决方案,包括性能改进以忽略重复的 max_counter 迭代:

                                          function solution(N, A) {
                                              let max = 0;
                                              let counters = Array(N).fill(max);
                                              let maxCounter = 0;
                                          
                                              for (let op of A) {
                                                  if (op <= N && op >= 1) {
                                                      maxCounter = 0;
                                                      if (++counters[op - 1] > max) {
                                                          max = counters[op - 1];
                                                      }
                                                  } else if(op === N + 1 && maxCounter === 0) {
                                                      maxCounter = 1;
                                                      for (let i = 0; i < counters.length; i++) {
                                                          counters[i] = max;   
                                                      }
                                                  }
                                              }
                                          
                                              return counters;
                                          }
                                          

                                          【讨论】:

                                            【解决方案24】:

                                            JAVA 中的解决方案 (100/100)

                                                class Solution {
                                                public int[] solution(int N, int[] A) {
                                                    // write your code in Java SE 8
                                                    int[] result = new int[N];
                                                    int base = 0;
                                                    int max = 0;
                                                    int needToChange=A.length;;
                                                    for (int k = 0; k < A.length; k++) {
                                                        int X = A[k];
                                                        if (X >= 1 && X <= N) {
                                            
                                                            if (result[X - 1] < base) {
                                                                result[X - 1] = base;
                                                            }
                                                            result[X - 1]++;
                                                            if (max < result[X - 1]) {
                                                                max = result[X - 1];
                                                            }
                                                        }
                                                        if (X == N + 1) {
                                                            base = max;
                                                            needToChange= X-1;
                                            
                                                        }
                                                    }
                                                    for (int i = 0; i < needToChange; i++) {
                                                        if (result[i] < base) {
                                                            result[i] = base;
                                                        }
                                                    }
                                                    return result;
                                            
                                                }
                                            
                                            }
                                            

                                            【讨论】:

                                              【解决方案25】:

                                              我的 Java 解决方案。它提供 100% 但很长(相比之下)。我使用 HashMap 来存储计数器。

                                              检测到的时间复杂度:O(N + M)

                                              import java.util.*;
                                              
                                              class Solution {
                                                final private Map<Integer, Integer> counters = new HashMap<>();
                                                private int maxCounterValue = 0;
                                                private int maxCounterValueRealized = 0;
                                              
                                                public int[] solution(int N, int[] A) {
                                                  if (N < 1) return new int[0];
                                              
                                                  for (int a : A) {
                                                    if (a <= N) {
                                                      Integer current = counters.putIfAbsent(a, maxCounterValueRealized + 1);
                                                      if (current == null) {
                                                        updateMaxCounterValue(maxCounterValueRealized + 1);
                                                      } else {
                                                        ++current;
                                                        counters.replace(a, current);
                                                        updateMaxCounterValue(current);
                                                      }
                                                    } else {
                                                      maxCounterValueRealized = maxCounterValue;
                                                      counters.clear();
                                                    }
                                                  }
                                              
                                                  return getCountersArray(N);
                                                }
                                              
                                                private void updateMaxCounterValue(int currentCounterValue) {
                                                  if (currentCounterValue > maxCounterValue)
                                                    maxCounterValue = currentCounterValue;
                                                }
                                              
                                                private int[] getCountersArray(int N) {
                                                  int[] countersArray = new int[N];
                                              
                                                  for (int j = 0; j < N; j++) {
                                                    Integer current = counters.get(j + 1);
                                                    if (current == null) {
                                                      countersArray[j] = maxCounterValueRealized;
                                                    } else {
                                                      countersArray[j] = current;
                                                    }
                                                  }
                                              
                                                  return countersArray;
                                                }
                                              }
                                              

                                              【讨论】:

                                                【解决方案26】:

                                                这是 100 % 的 python 解决方案 Codility Max counter 100%

                                                def solution(N, A):
                                                """
                                                Solution at 100% - https://app.codility.com/demo/results/trainingUQ95SB-4GA/
                                                Idea is first take the counter array of given size N
                                                take item from main A one by one + 1 and put in counter array , use item as index
                                                keep track of last max operation
                                                at the end replace counter items with max of local or counter item it self
                                                :param N:
                                                :param A:
                                                :return:
                                                """
                                                global_max = 0
                                                local_max = 0
                                                # counter array
                                                counter = [0] * N
                                                
                                                for i, item in enumerate(A):
                                                    # take item from original array one by one - 1 - minus due to using item as index
                                                    item_as_counter_index = item - 1
                                                    # print(item_as_counter_index)
                                                    # print(counter)
                                                    # print(local_max)
                                                    # current element less or equal value in array and greater than 1
                                                    #         if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
                                                    if N >= item >= 1:
                                                        # max of local_max counter at item_as_counter_index
                                                        # increase counter array value and put in counter array
                                                        counter[item_as_counter_index] = max(local_max, counter[item_as_counter_index]) + 1
                                                        # track the status of global_max counter so far
                                                        # this is operation K
                                                        global_max = max(global_max, counter[item_as_counter_index])
                                                    #         if A[K] = N + 1 then operation K is max counter.
                                                    elif item == N + 1:
                                                        # now operation k is as local max
                                                        # here we need to replace all items in array with this global max
                                                        # we can do using for loop for array length but that will cost bigo n2 complexity
                                                        # example -  for i, item in A: counter[i] = global_max
                                                        local_max = global_max
                                                    # print("global_max each step")
                                                    # print(global_max)
                                                
                                                # print("local max so far....")
                                                # print(local_max)
                                                # print("counter - ")
                                                # print(counter)
                                                # now counter array - replace all elements which are less than the local max found so far
                                                # all counters are set to the maximum value of any counter
                                                for i, item in enumerate(counter):
                                                    counter[i] = max(item, local_max)
                                                
                                                return counter
                                                

                                                结果 = 解决方案(1, [3, 4, 4, 6, 1, 4, 4]) print("Sol" + str(结果))

                                                【讨论】:

                                                  【解决方案27】:

                                                  enter link description here

                                                  使用 O ( N + M ) 获得 100% 的结果

                                                  class Solution {
                                                  public int[] solution(int N, int[] A) {
                                                      // write your code in Java SE 8
                                                  
                                                      int max = 0;
                                                      int[] counter = new int[N];
                                                      int upgrade = 0;
                                                  
                                                      for ( int i = 0; i < A.length; i++ )
                                                      {
                                                          if ( A[i] <= N )
                                                          {
                                                              if ( upgrade > 0 && upgrade > counter[A[i] - 1 ] )
                                                              {
                                                                  counter[A[i] - 1] = upgrade; 
                                                              }
                                                  
                                                              counter[A[i] - 1 ]++;
                                                  
                                                              if ( counter[A[i] - 1 ] > max )
                                                                  {
                                                                      max = counter[A[i] - 1 ];
                                                                  }
                                                          }
                                                          else
                                                          {
                                                              upgrade = max;
                                                          }
                                                  
                                                      }
                                                  
                                                      for ( int i = 0; i < N; i++ )
                                                      {
                                                          if ( counter[i] < upgrade)
                                                          {
                                                              counter[i] = upgrade;
                                                          }
                                                      }
                                                  
                                                      return counter;
                                                  
                                                  }
                                                  

                                                  }

                                                  【讨论】:

                                                    【解决方案28】:

                                                    Java 100%/100%,无导入

                                                    
                                                    public int[] solution(int N, int[] A) {
                                                    
                                                        int[] counters = new int[N];
                                                    
                                                        int currentMax = 0;
                                                        int sumOfMaxCounters = 0;
                                                        boolean justDoneMaxCounter = false;
                                                    
                                                        for (int i = 0; i < A.length ; i++) {
                                                    
                                                            if (A[i]  <= N) {
                                                    
                                                                justDoneMaxCounter = false;
                                                                counters[A[i]-1]++;
                                                                currentMax = currentMax < counters[A[i]-1] ? counters[A[i]-1] : currentMax;
                                                    
                                                            }else if (!justDoneMaxCounter){
                                                    
                                                                sumOfMaxCounters += currentMax;     
                                                                currentMax = 0;
                                                                counters = new int[N];
                                                                justDoneMaxCounter = true;
                                                    
                                                            }
                                                        }
                                                    
                                                    
                                                        for (int j = 0; j < counters.length; j++) {
                                                            counters[j] = counters[j] + sumOfMaxCounters;
                                                        }
                                                    
                                                        return counters;
                                                    }
                                                    

                                                    【讨论】:

                                                    • 您好,感谢您在 StackOverflow 上发表的第一篇文章。如果您不仅要发布代码,还要解释您更改具体内容的内容和原因,如果您想得到好的答案,那就太好了。
                                                    【解决方案29】:

                                                    python 解决方案:100% 100%

                                                    def solution(N, A):
                                                        c = [0] * N
                                                    
                                                        max_element = 0
                                                        base = 0
                                                        for item in A:
                                                    
                                                            if item >= 1 and N >= item:
                                                                c[item-1] = max(c[item-1], base) + 1
                                                                max_element = max(c[item - 1], max_element)
                                                            elif item == N + 1:
                                                                base = max_element
                                                    
                                                        for i in range(N):
                                                            c[i] = max (c[i], base)
                                                        return c
                                                        pass
                                                    

                                                    【讨论】:

                                                      【解决方案30】:

                                                      使用 applyMax 记录最大操作数

                                                      时间复杂度: O(N + M)

                                                      class Solution {
                                                          public int[] solution(int N, int[] A) {
                                                              // write your code in Java SE 8
                                                              
                                                              int max = 0, applyMax = 0;;
                                                              int[] result = new int[N];
                                                              
                                                              for (int i = 0; i < A.length; ++i) {
                                                                  int a = A[i];
                                                                  
                                                                  if (a == N + 1) {
                                                                      applyMax = max;
                                                                  }
                                                                  
                                                                  if (1 <= a && a <= N) {
                                                                      result[A[i] - 1] = Math.max(applyMax, result[A[i] - 1]);
                                                                      max = Math.max(max, ++result[A[i] - 1]);
                                                                  }
                                                              }
                                                              
                                                              for (int i = 0; i < N; ++i) {
                                                                  if (result[i] < applyMax) {
                                                                      result[i] = applyMax;
                                                                  }
                                                              }
                                                              
                                                              return result;
                                                          }
                                                      }
                                                      

                                                      【讨论】:

                                                        猜你喜欢
                                                        • 2013-12-28
                                                        • 1970-01-01
                                                        • 1970-01-01
                                                        • 2019-06-30
                                                        • 2020-09-19
                                                        • 2023-04-09
                                                        • 2022-06-03
                                                        • 2014-12-21
                                                        • 2016-06-25
                                                        相关资源
                                                        最近更新 更多