Algorithm to calculate number of intersecting discs

前端 未结 30 1515
鱼传尺愫
鱼传尺愫 2020-12-12 10:57

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius

30条回答
  •  借酒劲吻你
    2020-12-12 11:51

    Probably extremely fast. O(N). But you need to check it out. 100% on Codility. Main idea: 1. At any point of the table, there are number of circles "opened" till the right edge of the circle, lets say "o". 2. So there are (o-1-used) possible pairs for the circle in that point. "used" means circle that have been processed and pairs for them counted.

      public int solution(int[] A) { 
        final int N = A.length;
        final int M = N + 2;
        int[] left  = new int[M]; // values of nb of "left"  edges of the circles in that point
        int[] sleft = new int[M]; // prefix sum of left[]
        int il, ir;               // index of the "left" and of the "right" edge of the circle
    
        for (int i = 0; i < N; i++) { // counting left edges
          il = tl(i, A);
          left[il]++;
        }
    
        sleft[0] = left[0];
        for (int i = 1; i < M; i++) {// counting prefix sums for future use
          sleft[i]=sleft[i-1]+left[i];
        }
        int o, pairs, total_p = 0, total_used=0;
        for (int i = 0; i < N; i++) { // counting pairs
          ir = tr(i, A, M);
          o  = sleft[ir];                // nb of open till right edge
          pairs  = o -1 - total_used;
          total_used++;
          total_p += pairs;
        }
        if(total_p > 10000000){
          total_p = -1;
        }
        return total_p;
      }
    
        private int tl(int i, int[] A){
        int tl = i - A[i]; // index of "begin" of the circle
          if (tl < 0) {
            tl = 0;
          } else {
            tl = i - A[i] + 1;
          }
        return tl;
      }
      int tr(int i, int[] A, int M){
        int tr;           // index of "end" of the circle
          if (Integer.MAX_VALUE - i < A[i] || i + A[i] >= M - 1) {
            tr = M - 1;
          } else {
            tr = i + A[i] + 1;
          }
          return tr;
      }
    

提交回复
热议问题