LeetCode 2037.

Tags:

class Solution {
    public int minMovesToSeat(int[] seats, int[] students) {
        int result = 0;
        int[] sseats = mergeSort(0, seats.length-1, seats);
        int[] sstudents = mergeSort(0, seats.length-1, students);
        for (int i=0; i<seats.length; i++) {
            result += Math.abs(sstudents[i] - sseats[i]);
        }
        return result;
    }

    public int[] mergeSort(int start, int end, int[] arr) {
        int half = (int)((end - start) * 0.5);
        if (end - start < 2) {
            return cmp(start, end, arr);
        }
        return conquer(mergeSort(start, start + half, arr),
            mergeSort(start + half + 1, end, arr));
    }
    
    public int[] cmp(int start, int end, int[] arr) {
        if (end - start == 0) return new int[]{arr[start]};
        if (arr[end] < arr[start]) return new int[]{arr[end], arr[start]};
        return new int[]{arr[start], arr[end]};
    }

    public int[] conquer(int[] a, int[] b){
        int pta = 0, ptb = 0;
        int[] result = new int[a.length + b.length];
        while (pta < a.length && ptb < b.length) {
            if (a[pta] <= b[ptb]) {
                result[pta + ptb] = a[pta];
                pta++;
            }else{
                result[pta + ptb] = b[ptb];
                ptb++;
            }
        }
        if (pta == a.length) {
            for (int i=ptb; ptb<b.length; ptb++) {
                result[a.length+ptb]=b[ptb];
            }
        }else{
            for (int i=pta; pta<a.length; pta++) {
                result[b.length+pta]=a[pta];
            }
        }
        return result;
    }
}

Check out the description of this problem at LC 2037.