First solution (72%):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public int solution(int[] A) { // write your code in Java SE 8 int count = 0; for(int p=0; p<A.length; p++) { for(int q=p+1; q<A.length; q++) { if(A[p]>A[q]) count++; } } if(count > 1000000000) return -1; return count; } } |
Result : https://codility.com/demo/results/trainingXBUESU-MQG/
Second Solution (100%) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | // you can also use imports, for example: import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public int solution(int[] arr) { // write your code in Java SE 8 if (arr.length < 2) return 0; int m = (arr.length + 1) / 2; int left[] = Arrays.copyOfRange(arr, 0, m); int right[] = Arrays.copyOfRange(arr, m, arr.length); int result = solution(left) + solution(right) + merge(arr, left, right); if(result > 1000000000) return -1; return result; } int merge(int[] arr, int[] left, int[] right) { int i = 0, j = 0, count = 0; while (i < left.length || j < right.length) { if (i == left.length) { arr[i+j] = right[j]; j++; } else if (j == right.length) { arr[i+j] = left[i]; i++; } else if (left[i] <= right[j]) { arr[i+j] = left[i]; i++; } else { arr[i+j] = right[j]; count += left.length-i; j++; } } return count; } } |
Result : https://codility.com/demo/results/training57Y8R2-QK9/
No comments:
Post a Comment