2015-05-28 4 views
2

В тесте codility NumberOfDiscIntersections я получаю перфорация 100% и точность 87% с одного теста неисправного будучиNumberOfDiscIntersections в тесте codility

overflow 
arithmetic overflow tests 
got -1 expected 2 

Я не могу видеть, что является причиной, что, учитывая, что я использую длинный, который является 64-битным. И даже если я смогу довести его до 100% -ной корректности 100%, мне интересно, есть ли лучший способ сделать это, что не так много слов в Java.

редактировать: выяснял гораздо лучший способ сделать с двумя массивами, а не класс парного

// you can also use imports, for example: 
import java.util.*; 

// you can use System.out.println for debugging purposes, e.g. 
// System.out.println("this is a debug message"); 

class Solution { 
    public int solution(int[] A) { 
     int j = 0; 
     Pair[] arr = new Pair[A.length * 2]; 
     for (int i = 0; i < A.length; i++) { 
      Pair s = new Pair(i - A[i], true); 
      arr[j] = s; 
      j++; 
      Pair e = new Pair(i + A[i], false); 
      arr[j] = e; 
      j++; 
     } 
     Arrays.sort(arr, new Pair(0, true)); 

     long numIntersect = 0; 
     long currentCount = 0; 
     for (Pair p: arr) { 
      if (p.start) { 
       numIntersect += currentCount; 
       if (numIntersect > 10000000) { 
        return -1; 
       } 
       currentCount++; 
      } else { 
       currentCount--; 
      } 
     } 

     return (int) numIntersect; 
    } 

    static private class Pair implements Comparator<Pair> { 
     private long x; 
     private boolean start; 
     public Pair(long x, boolean start) { 
      this.x = x; 
      this.start = start; 
     } 

     public int compare(Pair p1, Pair p2) { 
      if (p1.x < p2.x) { 
       return -1; 
      } else if (p1.x > p2.x) { 
       return 1; 
      } else { 
       if (p1.start && p2.start == false) { 
        return -1; 
       } else if (p1.start == false && p2.start) { 
        return 1; 
       } else { 
        return 0; 
       } 
      } 
     } 
    } 
} 
+0

Вы можете добавить формулировку проблемы также? –

ответ

1

Посмотрите на этой линии:

Pair s = new Pair(i + A[i], true); 

Это эквивалентно Pair s = new Pair((long)(i + A[i]) , true);

Как i является целым числом, и A[i] также является целым числом, поэтому это может вызвать переполнение, поскольку значение в A[i] может g o до Integer.MAX_VALUE, а литье до long произошло после завершения операции добавления.

Чтобы исправить:

Pair s = new Pair((long)i + (long)A[i], true); 

Примечание: Я представил с моим фиксирован и получил 100%

https://codility.com/demo/results/demoRRBY3Q-UXH/

Смежные вопросы