For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
Have you met this question in a real interview?
Yes
Example
Given A =[2, 4, 1, 3, 5],(2, 1), (4, 1), (4, 3)are reverse pairs. return3
- naive way. for loop
public class Solution {
/**
* @param A an array
* @return total of reverse pairs
*/
public long reversePairs(int[] A) {
// Write your code here
if (A == null || A.length < 2) {
return 0;
}
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
for (int j = i + 1; j < A.length; j++) {
if (A[i] > A[j]) {
count++;
}
}
}
return count;
}
}