Home Codility. ArrayInversionCount
Post
Cancel

Codility. ArrayInversionCount

[Link] https://app.codility.com/programmers/trainings/4/array_inversion_count/


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
import java.util.*;

class Solution {
    public int solution(int[] A) {
        ArrayList<Integer> list = new ArrayList<>();
        int cnt = 0;
        list.add(A[0]);
        for(int i = 1; i < A.length; i++) {
            int insertIdx = findIdx(list, A[i]);
            if(insertIdx == list.size()) list.add(A[i]);
            else list.add(insertIdx, A[i]);
            cnt += insertIdx;
        }
        return cnt;
    }

    public int findIdx(ArrayList<Integer> list, int val) {
        int l = 0, r = list.size() - 1, mid;
        while(l <= r) {
            mid = (l + r) / 2;
            if(list.get(mid) > val) l = mid + 1;
            else if(list.get(mid) == val) return mid;
            else r = mid - 1;
        }
        return l;
    }
}
This post is licensed under CC BY 4.0 by the author.